之前我使用linq从数据库中获取数据,但看起来使用Linq的CompiledQuery应该比单独使用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"
}
答案 0 :(得分:1)
无法编译查询,因为“ToList”无法转换为sql。函数内部的任何内容都必须能够转换为sql。删除ToList并在调用编译的查询时使用它。
答案 1 :(得分:0)
感谢你的所有回复。 该异常已得到修复,但我从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.;
}
}