代码优先参考一对多

sad*_*t75 6 entity entity-framework fluent-interface code-first

我有以下两个表:

本土化

Id                     int
Text                   string
Run Code Online (Sandbox Code Playgroud)

DINER

Id                     int
Name                   string
Description            string
Name_LocalizationID    int
Description_LocationID int
Run Code Online (Sandbox Code Playgroud)

现在我希望我的POCO像这样:

public class Diner{
   public int Id{get;set;}
   public ICollection<Localization> NameLocalization{get;set;}
   public ICollection<Localization> DescriptionLocalization{get;set;} 
}

public class Localization{
   public int Id{get;set;}
   public string Text{get;set;}
}
Run Code Online (Sandbox Code Playgroud)

问题是:我们如何使用EF Fluent API将NameLocalization和DescriptionLocalization属性映射到Localization的Id?谢谢

Mor*_*avi 3

SQL Server 不支持多个级联删除,因此您需要将其中一个关联设置为可选,以便从对象模型派生 SQL Server 架构:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Diner>()
        .HasRequired(diner => diner.NameLocalization)
        .WithMany()
        .IsIndependent()
        .Map(s => 
        { 
            s.MapKey(localization => localization.Id, "NameLocalizationID"); 
        });

    modelBuilder.Entity<Diner>()
        .HasOptional(diner => diner.DescriptionLocalization)
        .WithMany()
        .IsIndependent()
        .Map(s => 
        { 
            s.MapKey(localization => localization.Id, "DescriptionLocationID"); 
        });
}
Run Code Online (Sandbox Code Playgroud)