为什么用创建lambda的函数替换IQueryable.Sum选择器中的lambda失败? (错误1025) [英] Why does replacing the lambda in a IQueryable.Sum selector with a function which creates the lambda fail? (Error 1025)
问题描述
我想抽象一个lambda函数,该函数根据状态汇总数据库中的记录.问题是,当我针对LINQ to Entities运行生成的lambda时,出现内部.NET Framework数据提供程序错误1025". (仅供参考,它对LINQ to Objects效果很好.)
I wanted to abstract a lambda function I have which sums up records in my DB based on their status. The problem is, when I run the generated lambda against LINQ to Entities, I get "Internal .NET Framework Data Provider error 1025." (FYI, it works fine against LINQ to Objects).
这是代码:
<Extension()> _
Public Function Summarize(ByVal auditsToSummarize As IQueryable(Of HvacAudit)) As IQueryable(Of HvacAuditSummary)
Return From audit In auditsToSummarize
Group By month = audit.DateCreated.Value.Month Into g = Group
Select New HvacAuditSummary With {
.GroupingKey = month,
.Pending = g.Sum(Function(audit) If(audit.AuditStatusInt = CType(AuditStatus.Pending, Integer), 1, 0)),
.Issued = g.Sum(Function(audit) If(audit.AuditStatusInt = CType(AuditStatus.Issued, Integer), 1, 0)),
.Closed = g.Sum(Function(audit) If(audit.AuditStatusInt = CType(AuditStatus.Closed, Integer), 1, 0)),
.Cancelled = g.Sum(Function(audit) If(audit.AuditStatusInt = CType(AuditStatus.Cancelled, Integer), 1, 0))
}
End Function
这是我尝试使用lambda生成器的示例:
And here's an example of how I try to use the lambda generator:
Select New HvacAuditSummary() With {
.Cancelled = g.Sum(AuditsWithStatus(AuditStatus.Cancelled))
}
Private Function AuditsWithStatus(auditStatus As AuditStatus) As Func(Of HvacAudit, Integer)
Return Function(audit) If(audit.AuditStatusInt = CType(auditStatus, Integer), 1, 0)
End Function
注意:我已经看过其他有关此错误的问题,它们似乎都集中在使用错误的LINQ上,因为使用了lambda(Func)代替了表达式.在sum方法中,所有候选人似乎都接受了Func,所以我不知道我还能改变什么.
NOTE: I have looked through other questions with this error, they all seem to focus on using the wrong LINQ because a lambda (Func) was used in place of an expression. In the sum method, all the candidates seem to take a Func, so I don't know what else I can change.
推荐答案
实体框架查询提供程序不知道您的函数AuditsWithStatus
. EF尝试将linq语句中的一切转换为sql,并且它只能处理一组有限的.Net函数,而这些函数都知道sql的等效项.其余的linq语句中的所有内容都必须是表达式(Expression<Func<...>>
).
The Entity Framework query provider does not know your function AuditsWithStatus
. EF tries to translate everything in your linq statement into sql, and it can only handle a restricted set of .Net functions of which it knows the sql equivalent. For the rest everything in the linq statement must be an expression (Expression<Func<...>>
).
这意味着:您可以使用函数,但只能在之后中使用ToList()
或ToArray()
,这会将其转换为linq-to-objects.或者,您必须将函数转换为表达式.
Which means: you can use your function but only after using ToList()
or ToArray()
, which turns it into linq-to-objects. Or you must turn your function into an expression.
这篇关于为什么用创建lambda的函数替换IQueryable.Sum选择器中的lambda失败? (错误1025)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!