How to configure multiple Foreignkey referancing to same table from main table using EF Code First Fluient API

给你一囗甜甜゛ 提交于 2019-12-04 15:28:41

You must manually remap each navigation property to define its key. Something like:

modelBuilder.Entity<Company>()
            .HasRequired(c => c.CountryCode)
            .WithMany()
            .HasForeignKey("CountryCodeID");

modelBuilder.Entity<Company>()
            .HasMany(c => c.CustomerCategoryCode)
            .WithOptional()
            .HasForeignKey("CustomerCategoryCodeID")
            .WillCascadeOnDelete(false);

modelBuilder.Entity<Company>()
            .HasMany(c => c.SupplierCategoryCode)
            .WithOptional()
            .HasForeignKey("SupplierCategoryCodeID")
            .WillCascadeOnDelete(false); 

It is not possible with data annotations unless you define navigation property and foreign key property in each dependent entity like:

public class Company
{
    ...

    [ForeignKey("CountryCode")]
    public virtual int CountryCodeID { get; set; }
    public CountryCode CountryCode { get; set; }
}

Inside your context class, you will need to override OnModelCreating and map the keys, it should look something like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
             modelBuilder.Entity<Company>()
                .HasRequired(c => c.CustomerCategoryCode)
                .WithMany() 
                .Map(mc => mc.MapKey("CustomerCategoryCodeID"));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!