为什么EF内核不能判断这个值

{log => (True AndAlso Invoke(log => log.Message.StartsWith("test"), log))}

and It gives me this error : "The LINQ expression 'log' 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'."
While this expression runs normally :

{log => (True AndAlso Invoke(log => log.Message.StartsWith(value(Project.Logging.Specs+<> c__DisplayClass1_1).message), log))}

当我使用And Also扩展方法将2表达式加在一起时会发生这种情况

Expression<Func<Logs, bool>> exp1 = log => true;
Expression<Func<Logs, bool>> exp2 = log => log.Message.Contains("message");

exp1 = exp1.AndAlso(exp);

public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right)
{
    var invokedExpr = Expression.Invoke(right, left.Parameters);
    return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(left.Body, invokedExpr), left.Parameters);
}

最后,我调用了dbContext

_context
  .Logs
  .Where(exp1);

推荐答案

找了复制品,但发现了一些过时的东西. 对于EF Core,您可以使用Microsoft.EntityFrameworkCore.Query.Internal命名空间中的ReplacingExpressionVisitor.

public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right)
{
    var visitor = new ReplacingExpressionVisitor(right.Parameters, left.Parameters);

    var rightBody = visitor.Visit(right.Body);
    var newPredicate = Expression.Lambda<Func<T, bool>>(Expression.AndAlso(left.Body, rightBody), left.Parameters);

    return newPredicate;
}

Csharp相关问答推荐

Blazor:用参数创建根路径

使用GeneratedComInterfaceProperty的.NET 8 COM类对于VB 6/SYS或ALEViewer不可见

Serilog SQL服务器接收器使用UTC作为时间戳

Blazor:类型或命名空间名称Components在命名空间中不存在''

有没有一种方法可以防止在编译时在MicrosoftC或非单线程上下文中调用方法?

Select Many和默认IfEmpty内部Select Many错误工作

只有第一个LINQ.Count()语句有效

使用Orleans进行的单元测试找不到接口的实现

在允许溢出的情况下将小数转换为长

C#-从基类更新子类

TagHelpers在新区域不起作用

EF核心新验证属性`DeniedValues`和`StringCompison`不起作用

实体框架-IsRequired()与OnDelete()

如何使用.NET Aspire从Blazor应用程序与GRPC API通信?

为什么Swashbakle/Swagger在参数中包含变量名?

Autofac -动态实例化:手动传递构造函数

如何在C# WinForm控件中使用Windows 10/11的黑暗主题?

在C#/ASP.NET Core 7中,什么可能导致POST请求作为GET请求发送

为什么我的属性即使没有显式地设置任何[必需]属性,也会显示验证?

.NET EF Core Automapper项目到筛选不起作用