简体   繁体   English

PredicateBuilder 不适用于 EF Core

[英]PredicateBuilder is not working on EF 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;
}

Just a piece of simple codes.只是一段简单的代码。 It throws me它把我扔了

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)

Below is my installed package下面是我安装的package

    <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" />

Any help would be appreciate.任何帮助将不胜感激。 Many thanks!非常感谢!

It seems that EF-core 5 doesn't play nice with AsExpandable .似乎 EF-core 5 与AsExpandable配合得不好。 Or rather the other way around.或者说反过来。 It worked with EF3, but apparently Linqkit isn't resilient to library-specific idiosyncrasies of expression trees.它与 EF3 一起工作,但显然 Linqkit 对特定于库的表达式树特性没有弹性。

There is a work-around for this case.这种情况有一个解决方法。 As expained here , predicate is not an Expression , but an ExpressionStarter , which implicitly converts to Expression<Func<T, bool>> and Func<T, bool> .正如这里所解释的, predicate不是一个Expression ,而是一个ExpressionStarter ,它隐式转换为Expression<Func<T, bool>>Func<T, bool> Therefore, queries with predicates on top-level entities (say: EF's IQueryables ) work without AsExpandable :因此,在顶级实体(例如:EF 的IQueryables )上使用谓词的查询在没有AsExpandable的情况下工作:

result = ctx.Assets   // No '.AsExpandable()'
    .Where(predicate) // Implicit conversion of 'predicate' to Expression<Func<Asset,boo>l>
    .Select(z => z.Symbol)
    .ToArray();

The bad news is that without any fixes in this area, you won't be able to use AsExpandable when it's really necessary, for example for predicates on collection navigation properties.坏消息是,如果在这方面没有任何修复,您将无法在真正需要时使用AsExpandable ,例如集合导航属性的谓词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM