【问题标题】:Generic Queries with Entity Framework使用实体框架的通用查询
【发布时间】:2010-09-04 22:16:25
【问题描述】:

我有一个包含大量查找实体的实体模型。都只有 ID 和 Name 属性。

我不想构建大量的 DAL 类来简单地拥有类似的东西:

IList<Lookup1> lookup1List= ctx.Lookup1.ToList();

和另一个带有

的类(或方法)
IList<Lookup2> lookup2List= ctx.Lookup2.ToList();

还有一个

IList<Lookup3> lookup3List= ctx.Lookup3.ToList();

我想要一种通用的方法来使用他们都实现的接口来查询所有这些。 像

IList<ILookupEntity> list = "SomeMethod"(Type lookupType);

我该怎么做?

【问题讨论】:

    标签: .net entity-framework entity-framework-4


    【解决方案1】:

    这个怎么样?

    public class Repository<T> where T : EntityObject, new()
    {
        public static IQueryable<T> List()
        {
            return EntityContext.Current.CreateObjectSet<T>();
        }
    }
    

    用法:

    var lookups = Repository<Lookup1>.List();
    

    【讨论】:

    • 有没有办法通过自我跟踪实体(不从 EntityObject 继承)来完成这项工作?
    【解决方案2】:

    所以你想查询所有实现特定接口的对象?目前我认为这是不可能的。

    【讨论】:

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