c# - 使用代码优先映射弱实体

标签 c# .net entity-framework ef-code-first entity-framework-5

您好,我已经开发出非常适合我的模型,现在我想使用 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中为ProductSupplier定义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/

相关文章:

c# - HTML accessDataSource 中的 ASP.NET 标签

c# - 将 JSON 值存储到具有有序键名的字典中

c# - 在IQueryProvider的实现中构造Linq.EnumerableQuery时出现编译器错误

c# - 模态形式的验证

c# - 不确定如何模拟 INancyModule.View 方法?

linq - 是否可以在没有LINQ的情况下使用 Entity Framework ?

.net - 使用 Triple DES 解密信息时出现错误数据

c# - 如何使用 .Net Windows 服务的新基本身份验证对 Visual Studio Team Services 进行身份验证?

c# - 使用 Automapper 将 DTO 映射到实体

c# - 分层数据的高级LINQ分组和投影查询(EF 4.0 + LINQ + ASP.NET MVC + HighCharts)