【问题标题】:How to OR combine two Expression for EF core [duplicate]如何或组合EF核心的两个表达式[重复]
【发布时间】:2021-10-23 23:12:24
【问题描述】:

我已经看过以下问题,但它并没有太大的吸引力,问题仍未解决。 How to combine (OR) two expression trees

你如何or-连接两个Expression<Func<T, bool>>

让我们考虑最简单的情况:

var fulltext = "some text";

private Expression<Func<User, bool>> FulltextSearch(string fulltext) {

    Expression<Func<User, bool>> left = t => t.Name.Contains(fulltext)
    Expression<Func<User, bool>> right = t => t.Description.Contains(fulltext)
    return Expression.Lambda<Func<Task, bool>>(Expression.Or(left.Body, right.Body), left.Parameters);
}

var users = dbContext.Users
    .Where(FulltextSearch("name xy"))
    .ToList();

这是一个简化的例子!

这以错误结束

System.InvalidOperationException: The LINQ expression 'DbSet<User>()
    .Where(t => t.Name.Contains(__fulltext_0) | t.Description.Contains(__fulltext_0))' 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'...

但是您可以像这样轻松编写此查询并且它可以工作:

var users = dbContext.Users
    .Where(u => u.Name.Contains(fulltext) || u.Description.Contains(fulltext))
    .ToList()

那么如何将两个 Expression> 合并为一个,以便 ef core 可以将其转换为 SQL?

【问题讨论】:

  • 您在使用针对您链接的问题提供的解决方案时遇到了什么问题?

标签: c# linq entity-framework-core


【解决方案1】:

Expression.Or 将转换为 按位 ORoperation(c# | 运算符)。 https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression.or?view=net-5.0
这将导致InvalidOperationException,因为它无法转换为 SQL。

Expression.OrElse 将转换为 逻辑 OR 操作。 (c#||运算符)https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression.orelse?view=net-5.0
这转换为 SQL 的 OR 运算符,是您在组合表达式时要使用的运算符。

【讨论】:

  • 你能把这些点连起来一点吗?您是说其中一个版本可以工作,但另一个版本不行?
  • @RobertHarvey 是的,OrElse 会起作用,Or 不会起作用。
  • 即使使用 OrElse 也无法正常工作。解决方案是编写自定义 ExpressionVisitor,正如其他副本所建议的那样。不知何故,我只是无法通过谷歌找到它......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多