PredicateBuilder 不适用于 EF Core

man*_*nok 5 c# predicatebuilder entity-framework-core .net-core

public string[] FindAssets2()
{
    string[] result;

    using (var ctx = new StockContext())
    {
        var predicate = PredicateBuilder.New<Asset>().Or(asset => asset.Symbol.Contains("TSLA"));

        result = ctx.Assets.AsExpandable()
        .Where(predicate)
        .Select(z => z.Symbol)
        .ToArray();
    }

    return result;
}
Run Code Online (Sandbox Code Playgroud)

只是一段简单的代码。它抛出我

Exception: Unhandled expression type: 'Extension'
LinqKit.ExpressionVisitor.Visit(Expression exp)
LinqKit.ExpressionVisitor.VisitExpressionList(ReadOnlyCollection<Expression> original)
LinqKit.ExpressionVisitor.VisitMethodCall(MethodCallExpression m)
LinqKit.ExpressionVisitor.Visit(Expression exp)
LinqKit.Extensions.Expand(Expression expr)
LinqKit.ExpandableQueryProvider<T>.System.Linq.IQueryProvider.CreateQuery<TElement>(Expression expression)
System.Linq.Queryable.Where<TSource>(IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
Run Code Online (Sandbox Code Playgroud)

下面是我安装的包

    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.0-preview.4.20220.10" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0-preview.4.20220.10" />
    <PackageReference Include="LINQKit.Core" Version="1.1.17" />
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激。非常感谢!

Ger*_*old 5

看来 EF-core 5 与AsExpandable. 或者更确切地说,相反。它可以与 EF3 一起使用,但显然 Linqkit 无法适应表达式树的库特定特性。

对于这种情况有一个解决方法。正如此处所解释的,predicate不是 an Expression,而是 an ExpressionStarter,它隐式转换为Expression<Func<T, bool>>and Func<T, bool>。因此,在顶级实体(例如:EF's IQueryables)上使用谓词的查询无需AsExpandable

result = ctx.Assets // 没有 '.AsExpandable()'
    .Where(predicate) // 将 'predicate' 隐式转换为 Expression<Func<Asset,boo>l>
    .Select(z => z.Symbol)
    .ToArray();

坏消息是,如果这方面没有任何修复,您将无法AsExpandable在真正需要时使用它,例如集合导航属性上的谓词。

  • 显然 EFC5 使用自定义表达式。表达式访问者应跳过此类表达式。LinqKit 已经过时了,问题确实存在,应该(如果)在那里修复,而不是在 EFC 中修复。 (3认同)