我试图修改表达式树用于动态创建一个包含表达式最终导致SQL像
P IN (123, 124, 125, 200, 201)
以代替检查执行范围检查,这最终导致SQL等
(P >= 123 AND P <= 125) OR (P >= 200 AND P <= 201)
我在我的基础上解决这个职位 。
static public Expression<Func<TElement, bool>>
BuildContainsExpression<TElement, TValue>(
Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values)
{
// Removed for post: Input checks and edge cases
var equals =
values.Select(value =>
(Expression)Expression.Equal(valueSelector.Body,
Expression.Constant(value, typeof(TValue))));
var body = equals.Aggregate<Expression>((accumulate, equal) =>
Expression.Or(accumulate, equal));
return Expression.Lambda<Func<TElement, bool>>(body, p);
}
我能够得到检查工作,如果我提供比较值的范围:
long testValue = 5;
List<KeyValuePair<int, int>> ranges = new List<KeyValuePair<int, int>>()
{
new KeyValuePair<long, long>(3, 6),
new KeyValuePair<long, long>(10, 12),
new KeyValuePair<long, long>(20, 20),
};
List<BinaryExpression> rangeExpressions = new List<BinaryExpression>();
foreach (var pair in ranges)
{
var greaterThanOrEqual =
Expression.GreaterThanOrEqual(Expression.Constant(testValue),
Expression.Constant(pair.Key));
var lessThanOrEqual =
Expression.LessThanOrEqual(Expression.Constant(testValue),
Expression.Constant(pair.Value));
var inRange = Expression.AndAlso(greaterThanOrEqual, lessThanOrEqual);
rangeExpressions.Add(inRange);
}
var final =
rangeExpressions.Aggregate<Expression>((a, b) => Expression.Or(a, b));
var result = Expression.Lambda<Func<bool>>(final).Compile()();
然而,我无法理清如何获取值从比较传入的表情时,我滴那个代码插入方法使用LINQ使用。 该方法的签名是:
Expression<Func<TElement, bool>>
BuildRangeExpression<TElement>(
Expression<Func<TElement, long>> valueSelector,
IEnumerable<long> values)
它用于这样的:
Expression<MyType, bool> match =
BuildRangeExpression<MyType, long>(my => my.ProductCode, productCodes);
var result = db.MyTypes.Where(match);
题
如何评估
Expression<Func<TElement, long>> valueSelector
所以,我可以使用传入值BuildRangeExpression
,而不是我目前硬编码的值
long testValue = 5;