【发布时间】: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 的外键,与Employees 和Genders 完全相同
我在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