0

我之前使用 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();
}

我只想从 table 中获取值“PC_ID”和“USER_ID” C_InternetCafe,并将它们添加到 myDataModel 其数据成员具有pidand uid

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

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

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"
}
4

2 回答 2

1

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

于 2012-08-31T04:44:22.977 回答
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.;
    }
}
于 2012-08-31T07:42:46.570 回答