Code-First Reference one-to-many

核能气质少年 提交于 2019-11-29 14:50:25

问题


I have the following two tables:

LOCALIZATION

Id                     int
Text                   string

DINER

Id                     int
Name                   string
Description            string
Name_LocalizationID    int
Description_LocationID int

Now I want my POCO like this:

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

Question is: How we can map NameLocalization and DescriptionLocalization property to Localization's Id with EF Fluent API? Thanks


回答1:


SQL Server does not support multiple cascade deletes, so you need to make one of your associations optional in order to derive a SQL Server schema from your object model:

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



回答2:


I've not tested this code, I'm afraid, but maybe something like:

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


来源:https://stackoverflow.com/questions/4939331/code-first-reference-one-to-many

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