Linq-to-entity, Generics and Precompiled Queries

I am experimenting with linq and generics. At the moment, I just implemented the GetAll method, which returns all records of this 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(); } } } 

It works great. Then 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 assume that the problem is related to the execution of a precompiled request, but I cannot understand why.

+6
source share
1 answer

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 request cannot call CreateObjectSet for the type TestEntity , because the precompiled request is not part of the context that is used to call it.

+4
source

Source: https://habr.com/ru/post/905505/


All Articles