Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code first parent child mapping

This may be a duplicate qn, but i couldnt get a proper answer to this scenario. I have the following table structure:

public class File
{
     public int FileId { get; set; } //PK
     public int VersionID { get; set; }

     public virtual ICollection<FileLocal> FileLLocalCollection { get; set; }
}

public class FileLocal
{
     public int FileId { get; set; } //PK, FK
     public int LangID { get; set; } //PK,FK
     public string FileName { get; set; }
}

I have not included the third table here(Its basically LangID (PK) & LangCode ) How do i specify this mapping in fluent Api so that i can load "FileLLocalCollection" with every File objects?

like image 739
user396491 Avatar asked Aug 26 '26 15:08

user396491


1 Answers

The first part of your mapping can be done this way:

modelBuilder.Entity<File>()
    .HasMany(f => f.FileLocalCollection)
    .WithRequired()
    .HasForeignKey(fl => fl.FileId);

modelBuilder.Entity<FileLocal>()
    .HasKey(fl => new {fl.FileId, fl.LangId});

And the second part depends on the way how your Lang is defined. For example if you add navigation property from FileLocal to Lang you can map it this way:

modelBuilder.Entity<FileLocal>()
    .HasRequired(fl => fl.Lang)
    .WithMany()
    .HasForeignKey(fl => fl.LangId);
like image 123
Ladislav Mrnka Avatar answered Aug 29 '26 02:08

Ladislav Mrnka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!