Question

I used the linq to fetch the data from database before, but it looks like using CompiledQuery with Linq should be than using Linq by itself.

I've try to use CompiledQuery, but it's throwing an exception.

Following is my code:

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();
}

I just want to fetch the values "PC_ID" and "USER_ID" from table C_InternetCafe, and add them to myDataModel whose datamember has pid and uid.

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

Forgive my negligence, the following are the exception I got.

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"
}
Was it helpful?

Solution

The query cannot be compiled because "ToList" cannot be translated into sql. Anything inside your function must be able to be converted to sql. Remove ToList and use it when calling the compiled query.

OTHER TIPS

Thx all your response. The exception has been fixed,but the list I converted from IQueryable has no data(not null, just count = 0).

The following are the code I modified...

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.;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top