EF 4.0基于泛型的继承 [英] EF 4.0 generics based inheritance

查看:129
本文介绍了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映射此层次结构?
目前生成的代码创建有一个错误,因为它生成一个属性,如

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;


推荐答案

我不这么认为是因为:


  • 继承映射要求基类是EDMX中的实体。

  • 当继承使用时, ObjectSet 用于基类型。您必须使用什么通用参数来创建一个 ObjectSet 的实例,当它必须用于检索任何子类型?

  • Inheritance mapping requires the base class to be entity in EDMX.
  • When inheritance is used the ObjectSet is for base type. What generic argument would you use to create an instance of ObjectSet when it has to be used to retrieve any subtype?

它可以部分实现没有继承(至少对于POCO)。简单地模拟您的子类型在EDMX没有基础类型。然后手动创建POCO类并从通用基类型派生它们。您必须遵循的唯一规则是POCO类必须与EDMX中的实体具有相同的名称,并且必须具有EDMX中具有辅助功能集的所有属性。如果要使用更改跟踪属性,必须将其标记为虚拟。如果你想使用延迟加载导航属性也必须是虚拟的。

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.

示例:

假设我在EDMX中有两个实体:IntegerValue和DoubleValue。现在我定义了这些POCO,如下所示:

Suppose that I have two entities in EDMX: IntegerValue and DoubleValue. Now I defined these POCOs as follows:

public abstract class BaseType<T>
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual T Value { get; set; }
}

public class IntegerValue : BaseType<int>
{ }

public class DoubleValue : BaseType<double>
{ }

它将导致每个子类型单表。

It will result in single table per sub type.

这篇关于EF 4.0基于泛型的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆