代码优先参考一对多

时间:2011-02-08 22:37:05

标签: entity-framework entity code-first fluent-interface

我有以下两个表:

LOCALIZATION

Id                     int
Text                   string

DINER

Id                     int
Name                   string
Description            string
Name_LocalizationID    int
Description_LocationID int

现在我希望我的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;}
}

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

2 个答案:

答案 0 :(得分: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"); 
        });
}

答案 1 :(得分:0)

我没有测试过这段代码,我担心,但可能会像:

modelBuilder.Entity<Diner>()
    .HasRequired(diner => diner.NameLocalization)
    .WithMany().IsIndependent()
    .Map(s => { s.MapKey(localization => localization.Id, "Name_LocalizationID"); });

modelBuilder.Entity<Diner>()
    .HasRequired(diner => diner.DescriptionLocalization)
    .WithMany().IsIndependent()
    .Map(s => { s.MapKey(localization => localization.Id, "Description_LocationID"); });