我之前使用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"
}发布于 2012-08-31 12:44:23
无法编译查询,因为无法将"ToList“转换为sql。您的函数中的任何内容都必须能够转换为sql。删除ToList并在调用编译后的查询时使用它。
发布于 2012-08-31 15:42:47
谢谢你所有的回复。异常已经修复,但我从IQueryable转换的列表没有数据(不是null,只是计数= 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.;
}
}https://stackoverflow.com/questions/12207982
复制相似问题