Error: The type ‘A’ cannot be mapped as defined because it maps
inherited properties from types that use entity splitting or another
form of inheritance. Either choose a different inheritance mapping
strategy so as to not map inherited properties, or change all types in
the hierarchy to map inherited properties and to not use splitting.
使用以下类时发生此错误:
public abstract class BaseEntityTest public abstract class BaseEntityTest2 : BaseEntityTest public abstract class BaseEntityTest3 : BaseEntityTest2 public class A: BaseEntityTest3 // this class is the only one with a table in the db
在OnModelCreating方法中,我添加了以下代码以获取TPC映射
modelBuilder.Entity<A>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("A");
});
当我从结构中排除BaseEntityTest2(这样A只从BaseEntityTest而不是BaseEntityTest2继承)时,错误消失了.这是否意味着无法创建此映射或我只是错过了什么?
编辑:
课程属性:
public abstract class BaseEntityTest
{
[Key]
public Guid Id { get; set; }
public String Info { get; set; }
[Required]
public DateTime CreationDate { get; set; }
[Required]
public String CreationUser { get; set; }
[Required]
public DateTime ModificationDate { get; set; }
[Required]
public String ModificationUser { get; set; }
[ConcurrencyCheck]
[Required]
public int LockVersion { get; internal set; }
}
public abstract class BaseEntityTest2 : BaseEntityTest
{
[Required]
public string Name { get; set; }
public string Description { get; set; }
}
public abstract class BaseEntityTest3: BaseEntityTest2
{
[Required]
public DateTime FromDate { get; set; }
public DateTime ThruDate { get; set; }
}
public class A: BaseEntityTest3{
public String Test { get; set; }
}
EF 4.3.1及更早版本发生错误,但EF 4.4和EF 5.0不发生错误. (EF 4.4实际上是EF 5.0,但是以.NET 4.0作为目标平台.)
但是:只有当您将抽象类用作模型中的实体时才会发生错误,这意味着
>你或者在你的上下文类中有他们的DbSets,比如
public DbSet<BaseEntityTestX> BaseEntityTestXs { get; set; }
>或者你有一些针对BaseEntityTestX的Fluent映射,一些是modelBuilder.Entity< BaseEntityTestX>()……的东西
>或者您正在使用其中一个BaseEntityTestX作为另一个(具体)实体类型中的导航属性
你需要这个吗?
具有DbSet< BaseEntityTestX>在你的上下文中只有在你真的想要查询其中一个抽象实体时才有意义,例如:
List<BaseEntityTest> list = context.BaseEntityTests
.Where(b => b.Info == "abc").ToList();
结果当然是从BaseEntityTest继承的具体实体的列表,但它可以是不同类型的混合,例如一些As和一些Bs.你需要这样的询问吗?或者您只想查询一些具体对象:
List<A> list = context.As
.Where(b => b.Info == "abc").ToList();
在后一种情况下,您不需要为抽象基类使用DbSet,也不需要任何继承映射.你可以删除DbSet< BaseEntityTestX>从您的上下文类中删除TPC映射,您的错误将消失.
最后一点 – 具有导航属性到另一个实体中的一个抽象实体 – 对于TPC映射没有意义.它只是不能映射到关系数据库,因为使用TPC映射时,抽象实体没有表,因此外键关系可以从具有navigation属性的具体类的表中引用.
如果将TPC映射扩展到基类,错误也将消失:
modelBuilder.Entity<BaseEntityTestX>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("BaseEntityTestX");
});
但它会为那些对我来说似乎没有意义的抽象实体创建表格.
