C# 如何使用CompiledQuery
我以前使用linq从数据库中获取数据,但看起来将CompiledQuery与linq结合使用应该比单独使用linq更好 我尝试使用CompiledQuery,但它引发了一个异常 以下是我的代码:C# 如何使用CompiledQuery,c#,database,entity,objectcontext,compiled-query,C#,Database,Entity,Objectcontext,Compiled Query,我以前使用linq从数据库中获取数据,但看起来将CompiledQuery与linq结合使用应该比单独使用linq更好 我尝试使用CompiledQuery,但它引发了一个异常 以下是我的代码: static readonly Func<myEntity, int?, List<myDataModel>> s_compiledQuery2 = CompiledQuery.Compile<myEntity, int?, List<myDataModel>&
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();
}
无法编译查询,因为无法将“ToList”转换为sql。函数中的任何内容都必须能够转换为sql。删除ToList并在调用编译后的查询时使用它。Thx所有响应。 异常已经修复,但是我从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.;
}
}
static readonly Func s_compiledQuery2=
CompiledQuery.Compile
(
(ctx,NULLUserId)=>
来自ctx.C_InternetCafe中的jlr
其中jlr.USER_ID!=NULLUserId
选择新的myDataModel
{
pid=jlr.PC_ID±0,
uid=jlr.USER\u ID??0
}
);
静态列表CompiledQuery2()
{
使用(myEntity context=new myEntity())
{
int?UserId=null;
IQueryable orders=s_compiledQuery2.Invoke(上下文,用户ID);
//orders的值=>orders.count()=762k
List tmpmodel=orders.ToList();
//tmpmodel没有值。=>orders.count()=0,为什么?
返回tmpmodel。;
}
}
发生了什么错误?我建议的第一件事是从已编译的查询体中删除ToList。
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.;
}
}