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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With