Linq-to-entities、泛型和预编译查询
我正在尝试 linq 和泛型。现在,我刚刚实现了一个 GetAll 方法,它返回给定类型的所有记录。
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();
}
}
}
这很好用。接下来,我想预编译查询:
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();
}
}
}
在这里,我得到以下信息:
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."}
这有什么问题?我猜问题出在预编译查询的执行结果上,但我无法想象为什么。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当我在 LINQ 查询中使用不属于实体模型的方法时,出现了此异常。问题在于预编译查询无法调用
TestEntity
类型的CreateObjectSet
,因为预编译查询不是用于调用它的上下文的一部分。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 typeTestEntity
because the precompiled query is not part of the context that is used to invoke it.