【问题标题】:Map weak entity by using Code first首先使用代码映射弱实体
【发布时间】:2013-02-04 12:02:18
【问题描述】:

您好,我开发了非常适合我的模型,现在我想使用 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 Supllier.ID 和 Product.Id 作为数据库关系的主键。

【问题讨论】:

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


    【解决方案1】:

    我使用数据注释,但我希望您正在寻找以下内容:

    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 });
    

    【讨论】:

    • 你会包含你使用的数据注释吗,@Moho?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    相关资源
    最近更新 更多