问题描述
我有以下模型:
public abstract class AbstractBase { }
public abstract class AbstractBase<T> : AbstractBase where T : SomeOtherTypeBase
{
T MyProp {get; set;}
}
public class Concrete1 : AbstractBase<OtherTypeSpecializationFor1> { }
public class Concrete2 : AbstractBase<OtherTypeSpecializationFor2> { }
但是实体框架给了我错误:
But entity framework gives me the error :
我认为这不会发生,因为AbstractBase直接继承自AbstractBase,而具体的类Concrete1/2则继承自GenericAbstractBase.这是怎么回事?
In my opinion this should not happen since AbstractBase directly inherits from AbstractBase and the classes Concrete1/2 which are concrete inherit from GenericAbstractBase. What's going on here ?
此外,出于好奇,我想知道EF是否会保留GenericAbstractBase中T类型的属性,以防万一经过的人想到了答案.
Also, just out of curiosity, I'm wondering if the property of type T in GenericAbstractBase would be persisted by EF, just in case someone passing by has the answer in mind.
更新1
任何人都可以确认EF支持吗?我已经看过,并且根据罗文的回答应该是这种情况.谢谢
Can anyone confirm that this is supported by EF ? I've seen this post and according to Rowan's answer's this should be the case.Thank you
更新2 通用基类不是抽象时,也会出现同样的问题.
Update 2Same issue when the generic base class is not abstract.
推荐答案
Here is the answer from the EF Team :
这样,您就可以从EF6运行时,您要添加三种不同且不相关的实体类型:AbstractBase,Concrete1和Concrete2.中的所有通用类型层次结构的中间位置已被忽略,因此EF不会知道他们之间有联系.
That way you have defined your DbContext, from the perspective of the EF6 runtime you are adding three different and unrelated entity types: AbstractBase, Concrete1 and Concrete2. All the generic types in the middle of the hierarchy have been ignored and therefore EF does not know that they are related.
请牢记这一限制,您得到的例外是预期的,因为AbstractBase是抽象的,并且没有任何内容具体的后代对EF很了解.如果您添加单独的非泛型和直接从AbstractBase继承的具体类型,例如:
With that limitation in mind, the exception you are getting is expected, since AbstractBase is abstract and does not have any concrete descendants know to EF. If you add a separate non-generic and concrete type that inherits directly from AbstractBase, e.g.:
public class ConcreteFork : AbstractBase { }
您的模型应该再次有效.但是您将无法使用MyContext.AbstractBases引导查询返回实例的查询Concrete1或Concrete2,因为EF并未意识到它们是相关.
Your model should be valid again. However you won't be able to use MyContext.AbstractBases to bootstrap queries that return instances of Concrete1 or Concrete2, as EF is unaware of the fact that they are related.
顺便说一句,在EF7中,我们摆脱了用于实现的EDM层EF,我们希望能够支持越来越多的场景,实际的通用实体类型.
希望这有助于解释发生了什么情况.
Hope this helps explain what is going on.
迭戈
这篇关于抽象类型X没有映射的后代,因此无法映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!