2012-01-09 31 views
6

我正在试验linq和泛型。现在,我刚刚实现了一个GetAll方法,该方法返回给定类型的所有记录。Linq-to-entities,泛型和预编译查询

class BaseBL<T> where T : class 
{ 
    public IList<T> GetAll() 
    { 
     using (TestObjectContext entities = new TestObjectContext(...)) 
     { 
      var result = from obj in entities.CreateObjectSet<T>() select obj; 
      return result.ToList(); 
     } 
    } 
} 

这工作正常。接下来,我想预编译查询:

class BaseBL<T> where T : class 
{ 
    private readonly Func<ObjectContext, IQueryable<T>> cqGetAll = 
    CompiledQuery.Compile<ObjectContext, IQueryable<T>>(
     (ctx) => from obj in ctx.CreateObjectSet<T>() select obj); 

    public IList<T> GetAll() 
    { 
     using (TestObjectContext entities = new TestObjectContext(...)) 
     { 
      var result = cqGetAll.Invoke(entities); 
      return result.ToList(); 
     } 
    } 
} 

在这里,我得到以下:

base {System.Exception} = {"LINQ to Entities does not recognize the method 
'System.Data.Objects.ObjectSet`1[admin_model.TestEntity] CreateObjectSet[TestEntity]()' 
method, and this method cannot be translated into a store expression."} 

这有什么问题吗?我想问题是执行预编译查询的结果,但我无法幻想为什么。

+0

为什么你认为你需要一个编译查询呢?你不需要它。 – 2012-01-09 09:55:27

+0

与错误无关;但如果它*工作,你会想''cqGetAll''静态字段 – 2012-01-09 10:00:53

+0

@Jeff梅尔卡多 - 我不需要它的这种情况下,但我打算扩大这与更复杂的查询 – loodakrawa 2012-01-09 10:02:51

回答

4

当我使用LINQ查询中不是实体模型的一部分的方法时,我有这个异常。问题在于,预编译查询无法调用TestEntity类型的CreateObjectSet,因为预编译查询不是用于调用它的上下文的一部分。

+0

似乎是这样。将预编译查询与CreateObjectSet结合使用时,我会遇到同样的异常。这意味着这与泛型没有任何关系。 – loodakrawa 2012-01-09 13:56:25