【问题标题】:Refactoring predicate out of the Lambda expressoin caueses an exception从 Lambda 表达式中重构谓词会导致异常
【发布时间】:2011-07-22 11:45:03
【问题描述】:

我有一个方法,它基于传入的参数构建一个大型 Lambda 表达式(用于 db 查询的过滤器,Entity Framework v. 1.0)。 假设我们有一个 Person、Department 和 Occupation 实体。 人可以有职业,职业属于一个部门。

代码如下:

var query = myDbContext.AsQueryable();
query = query.Persons.Where(.......) //Building some conditions
...
... //Adding conditions to the query if there are incoming params

问题出在以下片段:

//We have a Department Id as parameter, so we want to filter persons whose Occupations belong to this Department
query = query.Where(per => per.Occupations.Where(occ => !occ.IsDeleted).Count(occ => occ.Department.Id == myFilterParameter) > 0;)

这很好用,但是当从表达式中重构 Count() 构造的谓词时,如下所示:

Expression<Func<Occupation, bool>> countExpression = occ => occ.DepartmentId == myFilterParameter;
query = query.Where(per => per.Occupations.Where(occ => !occ.IsDeleted).Count(countExpression.Compile()) > 0);

导致

内部 .NET Framework 数据提供程序错误 1025。

你知道为什么会这样吗?

我也试过了:

query = query.Where(per => per.Occupations.Where(occ => !occ.IsDeleted).AsQueryable().Count(countExpression.Compile()) > 0), the same picture.

任何帮助都会非常感激。

【问题讨论】:

  • Any(occ =&gt; occ.Department.Id == myFilterParameter)代替Count(occ =&gt; occ.Department.Id == myFilterParameter) &gt; 0
  • 试过(occ =&gt; !occ.IsDeleted).Any(countExpression.Compile()),同样的例外:(

标签: c# linq entity-framework lambda


【解决方案1】:

错别字:

Expression&lt;Func&lt;Occupation, bool&gt;&gt; countExpression = occ =&gt; occ.DepartmentId = myFilterParameter;

这应该是:

Expression&lt;Func&lt;Occupation, bool&gt;&gt; countExpression = occ =&gt; occ.DepartmentId == myFilterParameter;

【讨论】:

    【解决方案2】:

    删除countExpression.Compile()上的Compile()

    编辑 - 你尝试过这样的事情吗?

    query.Where(per => per.Occupations
                          .Where(occ => !occ.IsDeleted)
                          .Any(countExpression));
    

    【讨论】:

    • 谢谢,这有助于避免错误 1025。但是出现了一个新错误。 Unable to create a constant value of type 'Closure type'. Only primitive types ('such as Int32, String, and Guid') are supported in this context. 调试时清除它,这个异常发生在代码后面,当 query.Count() 被调用时。
    • 也试过了:query.Where(per =&gt; per.Occupations.Where(occ =&gt; !occ.IsDeleted).AsQueryable().Any(countExpression));,同样的结果
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多