2012-08-31 106 views
0

我用linq從數據庫中獲取數據之前,但它看起來像使用與Linq的CompiledQuery應該比自己使用Linq。我怎樣才能使用CompiledQuery

我試過使用CompiledQuery,但它拋出一個異常。

以下是我的代碼:

static readonly Func<myEntity, int?, List<myDataModel>> s_compiledQuery2 = 
CompiledQuery.Compile<myEntity, int?, List<myDataModel>> 
(
    (ctx, NULLUserId) => 
    (
     from jlr in ctx.C_InternetCafe 
     where jlr.USER_ID != NULLUserId 
     select new myDataModel 
     { 
      pid = jlr.PC_ID ?? 0, 
      uid= jlr.USER_ID ?? 0 
     } 
    ).ToList() 
); 
static List<myDataModel> CompiledQuery2() 
{ 
    using (myEntity context = new myEntity()) 
    { 
     int? UserId = null; 
     List<myDataModel> orders = s_compiledQuery2.Invoke(context, UserId); 
     return orders; 
    } 
} 

public List<myDataModel> getCustomerInf() 
{ 
    return CompiledQuery2(); 
} 

我只是想從表C_InternetCafe獲取值「PC_ID」和「USER_ID」,並將其添加到myDataModel其數據成員有piduid

// -------------------------------------------- --------------------------------

原諒我的疏忽,以下是我得到的例外。

NotSupportedException 
{ 
    "LINQ to Entities does not recognize the method 
    'System.Collections.Generic.List`1 
    [InternetCafeManager.Web.DataModel.myDataModel] 
    ToList[myDataModel] 
    (System.Collections.Generic.IEnumerable`1 
    [InternetCafeManager.Web.DataModel.myDataModel])' method, 
    and this method cannot be translated into a store expression" 
} 
+0

有什麼錯誤?我建議的第一件事是從編譯的查詢體中刪除** ToList **。 – McGarnagle

回答

1

查詢無法編譯,因爲「ToList」無法轉換爲sql。你的函數中的任何內容都必須能夠轉換爲sql。刪除ToList並在調用編譯後的查詢時使用它。

0

Thx all your response。 異常已修復,但我從IQueryable轉換的列表沒有數據(不爲空,只是count = 0)。

以下是我修改了代碼...

static readonly Func<myEntity, int?, IQueryable<myDataModel>> s_compiledQuery2 = 
CompiledQuery.Compile<myEntity, int?, IQueryable<myDataModel>> 
(
    (ctx, NULLUserId) => 

     from jlr in ctx.C_InternetCafe 
     where jlr.USER_ID != NULLUserId 
     select new myDataModel 
     { 
      pid = jlr.PC_ID ?? 0, 
      uid = jlr.USER_ID ?? 0 
     } 

); 
static List<myDataModel> CompiledQuery2() 
{ 
    using (myEntity context = new myEntity()) 
    { 
     int? UserId = null; 
     IQueryable<myDataModel> orders = s_compiledQuery2.Invoke(context, UserId); 
     //orders has value => orders.count() = 762k 
     List<myDataModel> tmpmodel = orders.ToList<myDataModel>(); 
     //tmpmodel has no value. => orders.count() = 0, why? 
     return tmpmodel.; 
    } 
}