简体   繁体   中英

EF code first relation many models to one model

I try relashion 2 models to 1 model in Entity framework Code first like that:

one model: look at comments

public class File
{
    public int ID { get; set; }
    public int Model_ID { get; set; } // The id of the models
    public int Type_ID { get; set; } // When value is 1 its relate Lesson when 2 relate to Set
}

two models that relate File

public class Lesson
{
    public int ID { get; set; }
    public virtual File File { get; set; }
}

public class Set
{
    public int ID { get; set; }
    public virtual List<File> Files { get; set; }
}

DB example:

File Table

ID____Model_ID___Type_ID

1-----------123-------------1

2-----------123-------------2

When I select Lesson where ID = 123 its will take the file with Type_ID 1

Any idea how to map that?

Generally when you are using EF Code First mechanism it is good thing to think about object relations instead of tables. But if you really want to model your File class to be stored in one table you can achieve it by using inheritance:

public abstract class File
{
    public int ID { get; set; }
    public int Model_ID { get; set; } 
}

public class Lesson : File
{
}

public class Set : File
{
}

Entity framework will use its default Table Per Type inheritance strategy to represent those classes. However by default it will use text discriminator column with class name instead of integer Type_ID column. If you want to change this behavior you need to specify your own mapping to the Type property within your context class:

public class EntityFrameworkContext : DbContext
{
    public DbSet<File> Files { get; set; }
    public DbSet<Lesson> Lessons { get; set; }
    public DbSet<Set> Set { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<File>().Map<Lesson>(m => m.Requires("Type_ID").HasValue(1))
            .Map<Set>(m => m.Requires("Type_ID").HasValue(2));
    }
}

So now code like that will pick your record with Type_ID = 1

context.Lessons.Select(lesson => lesson.Model_ID == 123);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM