带有 EF.Functions.Like 的表达式树在扩展方法中使用时会产生错误

问题描述 投票:0回答:1

我可以成功运行这个方法。

db.Users.Where(x => arrayOfStringEmail.Any(email => EF.Functions.Like(x.Email, "%" + email + "%")))

但是当更改为扩展方法时会生成错误:

The LINQ expression 'x => x.Email' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

扩展方法如下:

public static IQueryable<TSource> WhereLike<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, object>> expression, params string[] words)
{
    return source.Where(x => words.Any(word => EF.Functions.Like(expression, "%" + word + "%")));
}

我想像这样使用它

db.Users.WhereLike(x => x.Email, arrayOfStringEmail);
c# entity-framework entity-framework-core
1个回答
0
投票

没有能力重现,但问题应该是由于参数表达式是按实例匹配的,而不是参数名称/类型匹配的。如果您不想手动构建谓词,您可以尝试替换表达式之一中的参数。像下面这样的东西(显然没有测试=)):

public static IQueryable<TSource> WhereLike<TSource>(this IQueryable<TSource> source, 
    Expression<Func<TSource, object>> expression, 
    params string[] words)
{
    Expression<Func<TSource,bool>> predicate = x => words.Any(word => EF.Functions.Like(expression, "%" + word + "%"));
    predicate = (Expression<Func<TSource,bool>>)(new ReplacingExpressionVisitor(expression.Parameters, predicate.Parameters).Visit(predicate));
    return source.Where(predicate);
}
© www.soinside.com 2019 - 2024. All rights reserved.