2012-01-09 28 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