使用导致异常的表达式过滤 EfCore DbSet

问题描述

尝试使用生成的表达式过滤动态 dbset 时

var expression = new ExpressionBuilder.ExpressionBuilder(BaseQuery.ElementType,TreeData.Filter).Build<T>();
Logger.LogDebug("Expression builder generated expression:\n{0}",expression.ToString());

BaseQuery = BaseQuery.Where(expression);
return this;

生成的表达式

expression.ToString()
"c => c.sources.Any(s => (s.Name == \"Intelligent Cotton Mouse\"))"

尝试执行 BaseQuery 时出现以下异常

system.invalidOperationException: The LINQ expression 'DbSet<Source>
    .Where(s => EF.Property<Nullable<Guid>>((EntityShaperExpression: 
        EntityType: Campaign
        ValueBufferExpression: 
            (ProjectionBindingExpression: EmptyProjectionMember)
        IsNullable: False
    ),"Id") != null && EF.Property<Nullable<Guid>>((EntityShaperExpression: 
        EntityType: Campaign
        ValueBufferExpression: 
            (ProjectionBindingExpression: EmptyProjectionMember)
        IsNullable: False
    ),"Id") == EF.Property<Nullable<Guid>>(s,"CampaignId"))
    .Any(s => s.Name == "Intelligent Cotton Mouse")' 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 either AsEnumerable(),AsAsyncEnumerable(),ToList(),or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

如果我尝试手动将生成的表达式插入到 .where()

    (BaseQuery as IQueryable<Campaign>).Where(c => 
                c.sources.Any(s => s.Name == "Intelligent Cotton Mouse"));

它有效,并且谓词成功转换为 sql。可能是什么问题?

解决方法

问题显然出在动态构建的表达式中,根据我的经验,我可以打赌它出在某些 ParameterExpression instances 中,例如 c 中使用的 c => {1}} 和 c.Sources,或 s 用于 s =>s.Name

请注意,ToString() 是在骗你,因为即使它们在视觉上看起来相同,但实际上它们不是 - lambda 表达式参数受实例约束,而不是名称,而且 lambda 表达式允许具有在构造过程中未绑定参数表达式,并且通常只有在尝试编译它们时才会生成错误。

这是为示例中的内部 Any 调用构建无效 lambda 表达式的示例(最后应该是生成有问题的异常,因为对外部执行相同的操作会给出不同的异常消息) :

var obj = Expression.Parameter(typeof(Source),"s");
var body = Expression.Equal(
    Expression.Property(obj,"Name"),Expression.Constant("Abc"));
var param = Expression.Parameter(typeof(Source),"s");
var expr = Expression.Lambda<Func<Source,bool>>(body,param);

注意 objparam 如何具有相同的名称和类型,但实例不同。即使没有错误并且 expr.ToString() 给出

s => (s.Name == "Abc")

试图在 LINQ 查询中使用这个表达式会产生运行时异常。


话虽如此,解决方案是修复表达式构建器代码以确保它使用正确的参数表达式。

例如,当从现有的 lambda 表达式组合时,它应该使用 Expression.Invoke 或自定义 ExpressionVisitor 用新参数替换正文中任何地方使用的原始参数。有很多示例可以说明如何做到这一点,例如 Combine two lambda expressions with inner expression