繁体   English   中英

EntityFramework 5代码优先多重继承映射(TPC)

[英]EntityFramework 5 Code First multiple inheritance mapping (TPC)

好吧,可能这个问题之前已经回答过了,但是我一直在研究中,但是我找不到我特定问题的解决方案

本示例的代码-Visual Studio 2012-控制台应用

所以我有一个带有多个继承对象的EntityFramework Code First模型。 我创建了一个代表我的问题的示例:

模型

public abstract class Person
{
    [Key]
    public Guid PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Employee : Person
{
    public decimal BaseSalary { get; set; }
}

public class ExecutiveEmployee : Employee
{
    public string Title { get; set; }
}

语境

public class MyContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<ExecutiveEmployee> ExecutiveEmployees { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>().Map(x =>
            {
                x.MapInheritedProperties();
                x.ToTable("Employees");
            });

        modelBuilder.Entity<ExecutiveEmployee>().Map(x =>
            {
                x.MapInheritedProperties();
                x.ToTable("ExecutiveEmployees");
            });
    }
}

我想使用TPC(每个具体类型的表格)映射

运行迁移并更新数据库后,结果如下:

在此处输入图片说明

这是我的期望。 到目前为止,一切都很好。

但是……。我决定像这样向我的Person类添加一个Gender对象和一个属性:(这不是我的真实模型,它只是一个示例)

public class Gender
{
    [Key]
    public Guid GenderId { get; set; }

    [Required]
    [MaxLength(250)]
    public string Name { get; set; }
}

public abstract class Person
{
    ....
    public Gender Gender { get; set; }
    ....
}

public class MyContext : DbContext
{
    ....
    public DbSet<Gender> Genders { get; set; }
    ....
 }

应用迁移并更新数据库后,这就是数据库模型:

在此处输入图片说明

WHYYYYYYYY?

我想念什么? 我只希望EF在继承层次结构中映射我的引用属性。 我期待的是, ExecutiveEmployees表包含一个外键Genders正是因为EmployeesGenders

我在MyContext.OnModelCreating上尝试过此MyContext.OnModelCreating

modelBuilder.Entity<ExecutiveEmployee>().Map(x =>
    {
        x.MapInheritedProperties();
        x.Properties(c => c.Gender);// <<-- does not work
        x.ToTable("ExecutiveEmployees");
    });

但是,当我尝试添加迁移时,出现此错误:

无法映射类型“ ExecutiveEmployee”上的属性“ Gender”,因为该属性已从模型中明确排除,或者所使用的DbModelBuilderVersion不支持该类型。

好吧,这很奇怪,我将您的示例放入了Visual Studio,并使用EF Power Tools来查看EDMX生成器如何可视化这些关系,这就是我得到的: 实体数据模型
从该图可以看到为什么会出错,因为现在实体框架假设导航属性已经在父类中找到。 现在,关于方式,我认为这是一个涉及TPC的Code First中的多级继承的错误,应予以修复。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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