[英]How to force SQL parameter instead of constant in Expression predicate
I want to create predicate expression so that it translates into WHERE clause with SQL parameter, eg:我想创建谓词表达式,以便将其转换为带有 SQL 参数的 WHERE 子句,例如:
WHERE e.Id = @id_1;
I have this code我有这个代码
int id = 1;
Expression<Func<Entity, int>> keySelector = e => e.Id;
BinaryExpression equals = Expression.Equal(
keySelector.Body,
Expression.Constant(id, keySelector.Body.Type)); //replace this with a variable
var predicate = Expression.Lambda<Func<Entity, bool>>(equals, keySelector.Parameters[0]);
but it translates into:但它转化为:
WHERE e.Id = 1;
which generates new query execution plan for each id.它为每个 id 生成新的查询执行计划。
Does EF core provide some internal mechanism, that I could (should) use, eg special subclass of Expression, or ExpressionVisitor? EF 核心是否提供一些我可以(应该)使用的内部机制,例如 Expression 的特殊子类或 ExpressionVisitor?
Does EF core provide some internal mechanism, that I could (should) use, eg special subclass of Expression, or ExpressionVisitor?
EF 核心是否提供一些我可以(应该)使用的内部机制,例如 Expression 的特殊子类或 ExpressionVisitor?
Nothing special.没什么特别的。 All you need is to emulate C# closure.
您只需要模拟 C# 闭包即可。 This could be done in several ways - using anonymous type, concrete type,
Tuple
or even real C# compiler generated closure like这可以通过多种方式完成——使用匿名类型、具体类型、
Tuple
甚至真正的 C# 编译器生成的闭包,例如
int id = 1;
Expression<Func<int>> valueSelector = () => id;
var value = valueSelector.Body; // use this in place of Expression.Constant
Example of anonymous type approach匿名类型方法的示例
int id = 1;
var variable = new { id };
var value = Expression.Property(Expression.Constant(variable), nameof(id));
Similar with new Tuple<int>(id)
and Item1
.与
new Tuple<int>(id)
和Item1
类似。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.