loo*_*awa 6 c# generics 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这很好用.接下来,我想预编译查询:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我得到以下内容:
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."}
Run Code Online (Sandbox Code Playgroud)
这有什么问题?我想问题是执行预编译查询的结果,但我无法想象为什么.
当我在 LINQ 查询中使用不属于实体模型的方法时,出现了此异常。问题在于预编译查询无法调用该CreateObjectSet类型的TestEntity,因为预编译查询不是用于调用它的上下文的一部分。