【问题标题】:EF - Extract all record of specific type table per hierarchyEF - 每个层次结构提取特定类型表的所有记录
【发布时间】:2016-10-21 21:45:38
【问题描述】:

在我的 EF 上下文中,我有一个类层次结构,使用按层次结构表的方法进行管理。

因此我有一个基础抽象类和一堆派生自它的类:

public abstract class BaseClass
{
    [Required]
    public int Id {get; set;}

    ...
}

public abstract class ExtendedClass1 : BaseClass
{

    ...

}

public abstract class ExtendedClass2 : BaseClass
{

    ...

}

类配置如下:

public class ExtendedClass1Configuration : 
    EntityTypeConfiguration<ExtendedClass1>
{
    ...

    this.Map(m => m.Requires("Discriminator").HasValue("ExtendedClass1"));
}

为了访问数据库,我使用派生自通用存储库的存储库:

public abstract class Repository<TEntity> : IRepository<TEntity> where TEntity: BaseClass
{
    protected DbContext context;

    DbSet<TEntity> GetSet()
    {
        return this.context.Set<TEntity>();
    }

    public virtual void Add(TEntity entity)
    {
        this.GetSet().Add(entity);
    }

    ...
}

public class BaseClassRepository : Repository<BaseClass>, IBaseClassRepository
{

    ...

}

我想向我的存储库添加一个方法,该方法将提取特定子类型的所有类(例如ExtendedClass1 类型的所有记录)。

我尝试了以下一些方法,但没有成功:

public IEnumerable<BaseClass> GetByType(Type type) {
    return context.Set<BaseClass>().OfType<type>();
}

这给了我以下编译错误:

找不到类型或命名空间名称“type”

我现在正在尝试的另一种方法是这样的:

public IEnumerable<TBaseClass> GetByType() where TBaseClass : BaseClass {
    return context.Set<BaseClass>().OfType<TBaseClass>();
}

我做错了什么?如何实现?

【问题讨论】:

  • OfType&lt;type&gt;(); 那是什么鬼? (如果不是错误)
  • 在 GetByType 方法中检查这一行:return context.Set().OfType();它应该是 return context.Set().OfType();类型名称不是变量。
  • 那行没有编译,只是为了让你知道我正在尝试的各种方法@Will
  • @KarelTamayo 我的想法是传递特定类型来提取,也许我需要使用泛型方法将类型作为泛型类型传递,但我没有做对
  • 这很让人分心.... 这并不优雅,但您可以使用msdn.microsoft.com/en-us/library/… 和/或msdn.microsoft.com/en-us/library/… 来确定实例是否属于您想要的祖先。哦,还有,public IEnumerable&lt;BaseClass&gt; GetByType&lt;T&gt;() { return context.Set&lt;BaseClass&gt;().OfType&lt;T&gt;();} 将是如何实现该方法(如果它按需要工作)

标签: c# entity-framework table-per-hierarchy


【解决方案1】:
public IEnumerable<BaseClass> GetByType(Type type) 
{
    return context.Set<BaseClass>().OfType<type>();
}

不正确,使用

public IEnumerable<BaseClass> GetByType<T>() 
{
    return context.Set<BaseClass>().OfType<T>();
}

类型参数ftw。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多