首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用CompiledQuery

如何使用CompiledQuery
EN

Stack Overflow用户
提问于 2012-08-31 09:58:49
回答 2查看 984关注 0票数 0

我之前使用linq从数据库中获取数据,但是看起来使用CompiledQuery和Linq应该比单独使用Linq更好。

我尝试过使用CompiledQuery,但它抛出了一个异常。

以下是我的代码:

代码语言:javascript
复制
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”,并将它们添加到数据成员分别为piduid的myDataModel中。

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

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

代码语言:javascript
复制
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"
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-08-31 12:44:23

无法编译查询,因为无法将"ToList“转换为sql。您的函数中的任何内容都必须能够转换为sql。删除ToList并在调用编译后的查询时使用它。

票数 1
EN

Stack Overflow用户

发布于 2012-08-31 15:42:47

谢谢你所有的回复。异常已经修复,但我从IQueryable转换的列表没有数据(不是null,只是计数= 0)。

以下是我修改过的代码...

代码语言:javascript
复制
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.;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12207982

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档