【发布时间】:2023-04-05 12:00:01
【问题描述】:
我第一次尝试预编译 linq 查询,看起来我做错了什么。
我想在验证器查询中使用预编译查询,每次使用最终会被调用大约 14k 次。我想在构造函数中实例化查询(同样,第一次使用这些,所以不确定这是否正确使用),因此类对象将能够调用编译后的查询。
这里是 Func 作为属性并在构造函数中实例化
private static Func<DataContext, ZipCodeTerritory, IQueryable<ZipCodeTerritory>> SearchEffectiveDate;
public ZipCodeValidatorCompiled()
{
SearchEffectiveDate = CompiledQuery.Compile((DataContext db, ZipCodeTerritory zipCode)
=>
from z in db.GetTable<ZipCodeTerritory>()
where z.DrmTerrDesc.Equals(zipCode.DrmTerrDesc) &&
z.IndDistrnId.Equals(zipCode.IndDistrnId) &&
z.StateCode.Equals(zipCode.StateCode) &&
(z.ZipCode.Equals(null) ? z.ZipCode.Equals(null) : z.ZipCode.Equals(zipCode.ZipCode))
select z
);
}
这是在其中一种验证方法中的调用方式
private static string ValidateEffectiveDate(ZipCodeTerritory zipCode)
{
using (var _db = new AgentResources())
{
IQueryable<ZipCodeTerritory> terrList = SearchEffectiveDate(_db, zipCode);
foreach (var zip in terrList)
{
if (zip.EffectiveDate >= zipCode.EndDate)
{
return
"End Date must be greater than Effective Date of any other record sharing the same DRM Territory Description, Territory, State and Zip Code; ";
}
}
}
return null;
}
我遇到的问题是验证方法中的这个语句
IQueryable<ZipCodeTerritory> terrList = SearchEffectiveDate(_db, zipCode);
Visual Studio SearchEffectiveDate(_db, zipCode) 给我以下错误:
- 错误 20 委托“System.Func>”有一些无效参数
- 错误 21 参数 1:无法从“Monet.Models.AgentResources”转换为“System.Data.Linq.DataContext”
我正在使用this tutorial 来加速 Linq 查询。
【问题讨论】:
-
仅供参考,查询的第一个参数不一定要定义为
DataContext,它可以从中派生。因此,您可以使用为您生成的数据上下文来代替它,这样您就可以在查询中进行更强大的输入。 -
你能改用
DbContext对象吗? -
不是直接的。 EF 的
DbContext不直接支持编译查询。但是你可以从中得到一个ObjectContext,它可以用于编译查询。将其转换为IObjectContextAdapter并获取ObjectContext以创建您的查询。我会看看如何为您的问题制定一个答案,它应该是可行的,只需进行一些调整。 -
再想一想,我想通过 EF 是不可能的。但在 EF5 中似乎不需要它。 stackoverflow.com/questions/9739925/…
标签: performance linq entity-framework linq-to-sql