Search code examples
c#databaseentityobjectcontextcompiled-query

How can I use CompiledQuery


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

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.