gpt4 book ai didi

c# - Linq-to-entities、泛型和预编译查询

转载 作者:太空狗 更新时间:2023-10-29 21:46:29 26 4
gpt4 key购买 nike

我正在试验 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."}

这有什么问题?我想问题出在预编译查询的执行结果上,但我无法理解为什么。

最佳答案

当我在 LINQ 查询中使用不属于实体模型的方法时,我遇到了这个异常。问题是预编译查询无法为 TestEntity 类型调用 CreateObjectSet,因为预编译查询不是用于调用它的上下文的一部分。

关于c# - Linq-to-entities、泛型和预编译查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8786457/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com