【发布时间】:2021-01-31 10:51:30
【问题描述】:
尝试使用生成的表达式过滤动态数据库集时
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。可能是什么问题?
【问题讨论】:
-
@AluanHaddad dbset 在运行时创建,我只能使用根据传递给方法的类型和条件生成的表达式
-
@AluanHaddad 我明白,但我必须使用表达式来保持方法动态
-
我的意思是 dbset 的实体可能不同,据我了解,如果我使用您的请求,那么我将绑定到一个实体
-
@AluanHaddad 过滤的表达式已经生成了,我就是不明白为什么我手写的谓词和生成的谓词不等价
标签: c# linq entity-framework-core expression-trees ef-core-3.1