基于 EF 4.0 泛型的继承
我有一个这样的类
public abstract class BaseType<T>
{
public string Name {};
public T TypedValue {
get {
return GetTypedValue(PersistedValue);
}
};
public string PersistedValue {}
public abstract T GetTypedValue(PersistedValue);
}
,然后有许多派生类,例如
public class IntegerType:BaseType<int>
{
...
}
是否可以使用 EF 4.0 使用每个继承方案的表来映射此层次结构? 目前生成的代码创建有一个错误,因为它生成了一个类似的属性
public <T> ObjectSet<TypedAttribute<T>> TypedAttributes
{
get
{
return _typedAttributes ?? (_typedAttributes = CreateObjectSet<TypedAttribute<T>>("TypedAttributes")); }
}
private ObjectSet<TypedAttribute> _typedAttributes;
I have a class like this
public abstract class BaseType<T>
{
public string Name {};
public T TypedValue {
get {
return GetTypedValue(PersistedValue);
}
};
public string PersistedValue {}
public abstract T GetTypedValue(PersistedValue);
}
then many derived classes like
public class IntegerType:BaseType<int>
{
...
}
is it possible to map this hierarchy using EF 4.0 using Table per inheritance scheme ?
Currently the generated code creates has an error because it generates a property like
public <T> ObjectSet<TypedAttribute<T>> TypedAttributes
{
get
{
return _typedAttributes ?? (_typedAttributes = CreateObjectSet<TypedAttribute<T>>("TypedAttributes")); }
}
private ObjectSet<TypedAttribute> _typedAttributes;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不这么认为,因为:
ObjectSet
用于基本类型。当必须使用 ObjectSet 来检索任何子类型时,您将使用什么通用参数来创建它的实例?无需继承即可部分实现(至少对于 POCO 而言)。只需在 EDMX 中对子类型进行建模,无需基本类型。然后手动创建 POCO 类并从通用基类型派生它们。您必须遵循的唯一规则是 POCO 类必须与 EDMX 中的实体具有相同的名称,并且它的所有属性必须在 EDMX 中设置可访问性。如果要使用更改跟踪属性,必须将其标记为虚拟。如果你想使用延迟加载导航属性也必须是虚拟的。
示例:
假设我在 EDMX 中有两个实体:IntegerValue 和 DoubleValue。现在我将这些 POCO 定义如下:
它将导致每个子类型生成一个表。
I don't think so because:
ObjectSet
is for base type. What generic argument would you use to create an instance ofObjectSet
when it has to be used to retrieve any subtype?It can be partially achieved without inheritance (at least for POCOs). Simply model your subtypes in EDMX without base type. Then manually create POCO classes and derive them from generic base types. The only rule you have to follow is that POCO class must have the same name as entity in EDMX and it must have all its properties with accessibility set in EDMX. If you want to use change tracking properties must be marked as virtual. If you want to use lazy loading navigation properties must be virtual as well.
Example:
Suppose that I have two entities in EDMX: IntegerValue and DoubleValue. Now I defined these POCOs as follows:
It will result in single table per sub type.