Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code-First Reference one-to-many

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

like image 579
sadhat75 Avatar asked Feb 08 '11 22:02

sadhat75


1 Answers

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"); 
        });
}
like image 125
Morteza Manavi Avatar answered Sep 21 '22 17:09

Morteza Manavi