[英]How can I use CompiledQuery
我以前使用過linq從數據庫中獲取數據,但是看起來將CompiledQuery與Linq一起使用應該比單獨使用Linq更好。
我嘗試使用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”,並將它們添加到其數據成員具有pid
和uid
的myDataModel中。
// ------------------------------------------------ ----------------------------
原諒我的疏忽,以下是我所獲得的例外。
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"
}
無法編譯查詢,因為“ ToList”無法轉換為sql。 函數內部的任何內容都必須能夠轉換為sql。 刪除ToList並在調用編譯查詢時使用它。
感謝您的所有回應。 異常已得到修復,但是我從IQueryable轉換的列表中沒有數據(不為null,只有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.;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.