您好,我已经开发出非常适合我的模型,现在我想使用 EntityFramework 将它映射到数据库,这是它的一部分:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ProductType Type { get; set; }
}
public class Supplier
{
public int Id { get; set; }
public string OIB { get; set; }
public string Name { get; set; }
}
public class SupplierProduct
{
public double Price { get; set; }
public string SupplierMark { get; set; }
public virtual Product Product { get; set; }
public virtual Supplier Supplier { get; set; }
}
现在我的问题是如何从我的 DBContext 在 ModelBuilder 上编写实体配置,以便它映射到 SupplierProduct 类 ForeignKeys Supplier.ID 和 Product.Id 作为数据库关系的主键。
最佳答案
我使用数据注释,但我希望您正在寻找以下内容:
在SupplierProduct
中为Product
和Supplier
定义ID属性,将这些ID字段指定为FK,然后用这两个ID定义复合主键字段
modelBuilder.Entity<SupplierProduct>()
.HasRequired( sp => sp.Product)
.WithMany( p => SupplierProducts )
.HasForeignKey( sp => sp.ProductId );
modelBuilder.Entity<SupplierProduct>()
.HasRequired( sp => sp.Supplier)
.WithMany( s => SupplierProducts )
.HasForeignKey( sp => sp.SupplierId );
modelBuilder.Entity<SupplierProduct>()
.HasKey(sp=> new { sp.ProductId, sp.SupplierId });
关于c# - 使用代码优先映射弱实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14686367/