dotnet data_error ai_generated true

System.InvalidOperationException: 为查询过滤器 'FilterName' 生成了错误。筛选器表达式必须是可应用于实体类型 'EntityType' 的 LambdaExpression。

System.InvalidOperationException: An error was generated for the query filter 'FilterName'. The filter expression must be a LambdaExpression that can be applied to the entity type 'EntityType'.

ID: dotnet/ef-core-query-filter-parameter-mismatch

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
1证据数
2023-06-15首次发现

版本兼容性

版本状态引入弃用备注
6.0 active
7.0 active
8.0 active
9.0 active

根因分析

Entity Framework Core 查询过滤器使用了参数化表达式,引用了实体模型上不可用的属性或方法,通常是由于缺少导航属性或 Lambda 语法错误。

English

Entity Framework Core query filter uses a parameterized expression that references a property or method not available on the entity's model, often due to a missing navigation property or incorrect lambda syntax.

generic

官方文档

https://learn.microsoft.com/en-us/ef/core/querying/filters

解决方案

  1. Rewrite the query filter in OnModelCreating to use a simple lambda without complex expressions. For example, change 'modelBuilder.Entity<Blog>().HasQueryFilter(b => b.TenantId == _tenantProvider.GetTenantId())' to 'modelBuilder.Entity<Blog>().HasQueryFilter(b => b.TenantId == 1)' and pass the tenant ID via a constructor parameter.
  2. Ensure that any method used in the filter is a static method or property accessible at the model level. Replace instance methods with static equivalents: 'b => b.IsDeleted == false' instead of 'b => _service.IsDeleted(b)'.

无效尝试

常见但无效的做法:

  1. 60% 失败

    Removing the filter entirely may break business logic that requires soft-delete or multi-tenant isolation.

  2. 80% 失败

    Adding .Include() to eager-load navigation properties does not fix the filter expression itself; the filter must be corrected at the model level.

  3. 70% 失败

    Changing the entity's base class or interface does not address the lambda parameter mismatch; the filter must be rewritten.