LINQ to Entities:在 where 条件下无法识别可查询扩展方法

LINQ to Entities: queryable extension method not reconized inside where condition

我正在使用 asp.net 4.5 mvc 5,代码优先 entity framework 并且遇到以下问题:

我有两个型号,"PostBody" 和 "PostHeader"。 1 个 PostHeader 有 1-n 个 PostBodies。 PostBody 可以是 "Deleted"(属性 作为标志)。

我的扩展方法应该为我提供来自 IQueryable 对象的每个 PostBody,该对象未作为 IQueryable 删除:

    public static IQueryable<TSource> GetActiveVersions<TSource>(this IQueryable<TSource> source)
       where TSource : PostBody
    {
        return source.Where(x => x.Deleted == false);
    }

当我这样做时,它工作正常

var x = db.Bodies.GetActiveVersions().ToList();

或这个

var y = db.Headers.FirstOrDefault().Bodies.AsQueryable().GetActiveVersions().ToList();

等- 但是一旦我使用我的扩展方法作为表达式参数的一部分,例如where 方法,我 运行 进入 NotSupportedException:

var z = db.Headers.Where(h => h.Bodies.AsQueryable().GetActiveVersions().Count() > 0).ToList();

System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[WebApplication5.Models.PostBody] GetActiveVersions[PostBody](System.Linq.IQueryable`1[WebApplication5.Models.PostBody])' method, and this method cannot be translated into a store expression.

我做错了什么?或者 - 我如何在 where 条件下使用我的扩展方法?

可能解析器无法解析 linq 表达式中的扩展方法。您可以尝试集中您的条件并将其用作表达式树,例如:

public static Expression<Func<TSource, bool>> GetActiveVersions()
    where TSource : PostBody
{
  return x => x.Deleted == false;
}

并在您的子查询(使用 linq)中应用此表达式作为示例:

var z = db.Headers.Where(h => h.Bodies.AsQueryable().Any(GetActiveVersions())).ToList();

而不是使用 Count() > 0,更喜欢使用 .Any() 以避免访问 table 的所有记录。