C# EF代码首先将多个模型关联到一个模型

C# EF代码首先将多个模型关联到一个模型,c#,entity-framework,c#-4.0,ef-code-first,C#,Entity Framework,C# 4.0,Ef Code First,我首先尝试在实体框架代码中将2个模型与1个模型重新关联,如下所示: 一种模式: 看看评论 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

我首先尝试在实体框架代码中将2个模型与1个模型重新关联,如下所示:

一种模式: 看看评论

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
}
两个与文件相关的模型

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; }
}
公共课
{
公共int ID{get;set;}
公共虚拟文件{get;set;}
}
公共类集
{
公共int ID{get;set;}
公共虚拟列表文件{get;set;}
}
DB示例:

文件表

ID \型号\ ID \类型\ ID

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

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

当我选择Lesson where ID=123时,它将接受类型为\u ID 1的文件


知道如何映射吗?

通常,当您使用EF代码优先机制时,最好考虑对象关系而不是表。但是,如果您确实希望将文件类建模为存储在一个表中,则可以通过使用继承来实现:

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

public class Lesson : File
{
}

public class Set : File
{
}
实体框架将使用其默认的每类型表继承策略来表示这些类。但是,默认情况下,它将使用具有类名的文本鉴别器列,而不是整型\u ID列。如果要更改此行为,需要在上下文类中指定自己到Type属性的映射:

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));
    }
}
如果我想在第一课中列出,这对我没有帮助:\
context.Lessons.Select(lesson => lesson.Model_ID == 123);