Map weak entity by using Code first

我的未来我决定 提交于 2019-12-11 00:49:07

问题


Hi I have developed model that works perfectly for me, now I want to map it to database using EntityFramework, here is a part of it:

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

Now my question is how do I write entity configuration on ModelBuilder form my DBContext so that it maps on SupplierProduct class ForeignKeys Supllier.ID and Product.Id as Primary key of DB relation.


回答1:


I use data annotations, but I expect you're looking for the following:

define ID properties for Product and Supplier in SupplierProduct, specify these ID fields as FK's, then define compound primary key with the two ID fields

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


来源:https://stackoverflow.com/questions/14686367/map-weak-entity-by-using-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!