【问题标题】:EntityFramework 5 Code First multiple inheritance mapping (TPC)EntityFramework 5 Code First 多重继承映射 (TPC)
【发布时间】:2013-03-04 15:28:01
【问题描述】:

好吧,这个问题可能以前已经回答过,但我一直在研究,我只是找不到解决我具体问题的方法

Code of this sample - Visual Studio 2012 - Console App

所以我有一个具有多个继承对象的 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 (Table Per Concrete Type) mapping

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

这是我的期望。到目前为止一切顺利。

但后来....... 我决定向我的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 在我的继承层次结构中映射我的 reference 属性。我期望ExecutiveEmployees 表包含Genders 的外键,与EmployeesGenders 完全相同

我在MyContext.OnModelCreating 上试过这个:

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

但是当我尝试添加迁移时,我收到了这个错误:

无法映射类型“ExecutiveEmployee”上的属性“Gender”,因为它已从模型中显式排除,或者它属于正在使用的 DbModelBuilderVersion 不支持的类型。

【问题讨论】:

  • 我在 EF 中发布了一个错误:entityframework.codeplex.com/workitem/1049
  • 我从 EF 错误报告中阅读了信息:“但是,如果使用 FK 关联,则可以映射这种类型的关系。” - 因此,如果您将 Person 类中的 [ForeignKey] 字段添加到 Gender 它应该可以工作(如果我理解正确的话)?您是否尝试过他们的解决方案?

标签: c# entity-framework ef-code-first entity-framework-5 entity-framework-mapping


【解决方案1】:

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

【讨论】:

  • 有道理,我也是这么想的。由于 EF 映射的是我的值类型而不是我的引用类型,这种行为让我认为这是一个错误 =((
猜你喜欢
  • 2012-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多