Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq-to-entities, Generics and Precompiled Queries

I'm experimenting with linq and generics. For now, I just implemented a GetAll method which returns all records of the given type.

class BaseBL<T> where T : class
{
    public IList<T> GetAll()
    {
        using (TestObjectContext entities = new TestObjectContext(...))
        {
            var result = from obj in entities.CreateObjectSet<T>() select obj;
            return result.ToList();
        }
    }
}

This works fine. Next, I would like to precompile the query:

class BaseBL<T> where T : class
{
    private readonly Func<ObjectContext, IQueryable<T>> cqGetAll =
    CompiledQuery.Compile<ObjectContext, IQueryable<T>>(
      (ctx) => from obj in ctx.CreateObjectSet<T>() select obj);

    public IList<T> GetAll()
    {
        using (TestObjectContext entities = new TestObjectContext(...))
        {
            var result = cqGetAll.Invoke(entities);
            return result.ToList();
        }
    }
}

Here, i get the following:

 base {System.Exception} = {"LINQ to Entities does not recognize the method
'System.Data.Objects.ObjectSet`1[admin_model.TestEntity] CreateObjectSet[TestEntity]()'
 method, and this method cannot be translated into a store expression."}

What is the problem with this? I guess the problem is with the result of the execution of the precompiled query, but I am unable to fanthom why.

like image 870
loodakrawa Avatar asked Jan 09 '12 09:01

loodakrawa


1 Answers

I had this exception when I used methods inside the LINQ query that are not part of the entity model. The problem is that the precompiled query can't invoke the CreateObjectSet for the type TestEntity because the precompiled query is not part of the context that is used to invoke it.

like image 181
Mentoliptus Avatar answered Sep 28 '22 02:09

Mentoliptus