EF Core 全局查询过滤器复杂表达式

EF Core Global Query Filter Complex expression

我正在尝试在我的应用程序中实现一个全局查询过滤器。我有 AssessmentModels 可以有多个所有者,这些所有者来自我无法完全控制的第 3 方,但可以根据需要进行调整。 (并且可以在我保存到我的数据库之前进行操作)现在,Owners 存储为分号分隔的字符串(例如,team1;team2)。

我想出了以下适用于选择数据但不适用于全局查询过滤器的方法:

private Expression<Func<AssessmentModel, bool>> GetAssessmentFilter()
{
    // The lambda parameter.
    var assessmentParameter = Expression.Parameter(typeof(AssessmentModel), "a");
    // Build the individual conditions to check against.
    var orConditions = _adminTeamNames
        .Select(keyword => (Expression<Func<AssessmentModel, bool>>)(a => EF.Functions.Like(a.Owners, $"%{keyword}%")))
        .Select(lambda => (Expression)Expression.Invoke(lambda, assessmentParameter))
        .ToList();

    // Combine the individual conditions to an expression tree of nested ORs.
    var orExpressionTree = orConditions
        .Skip(1)
        .Aggregate(
            orConditions.First(),
            (current, expression) => Expression.OrElse(expression, current));


    // Build the final predicate (a lambda expression), so we can use it inside of `.Where()`.
    var predicateExpression = (Expression<Func<AssessmentModel, bool>>)Expression.Lambda(
        orExpressionTree,
        assessmentParameter);

    return predicateExpression;
}

所以, var result = db.Assessments.Where(predicateExpression).ToList(); 有效,但 modelBuilder.Entity<AssessmentModel>().HasQueryFilter(predicateExpression); 给出错误:

System.InvalidOperationException : The LINQ expression 'DbSet<AssessmentModel>()
.Where(a => Invoke(a => value(DbFunctions).Like(a.Owners, "%Los%"), a)
 || Invoke(a => value(DbFunctions).Like(a.Owners, "%Atl%"), a)
)' 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.

AFAIK EF Core 不太擅长翻译调用表达式。尝试用您的自定义参数表达式(即 assessmentParameter)手动替换构建 lambda 的参数:

var orConditions = _adminTeamNames
    .Select(keyword => (Expression<Func<AssessmentModel, bool>>)(a => EF.Functions.Like(a.Owners, $"%{keyword}%")))
    .Select(lambda => new ReplacingExpressionVisitor(lambda.Parameters, new []{assessmentParameter}).Visit(lambda.Body))
    .ToList();