参数化 Linq 表达式帮助
我想做一个具有如下签名的方法:
Expression<Func<TSource, bool>> CreatePropertyFilter<TSource>(Expression<Func<TSource, string>> selector, string value, TextMatchMode matchMode);
基本上,它需要一个属性选择器(例如:p = p.Name
)、一个字符串值和一个可以是 StartsWith 的枚举值
、EndsWith
、包含
、精确
;用于文本匹配选项。
如何以 LINQ2Entities 可以理解的方式实现该方法?我已经使用嵌套调用表达式实现了该方法,如下所示:
Expression<Func<string, bool>> comparerExpression;
switch (matchMode)
{
case TextMatchMode.StartsWith:
comparerExpression = p => p.StartsWith(value);
break;
case TextMatchMode.EndsWith:
comparerExpression = p => p.EndsWith(value);
break;
case TextMatchMode.Contains:
comparerExpression = p => p.Contains(value);
break;
default:
comparerExpression = p => p.Equals(value);
break;
}
var equalityComparerParameter = Expression.Parameter(typeof(IncomingMail), null);
var equalityComparerExpression = Expression.Invoke(comparerExpression, Expression.Invoke(selector, equalityComparerParameter));
var equalityComparerPredicate = Expression.Lambda<Func<IncomingMail, bool>>(equalityComparerExpression, equalityComparerParameter);
问题是 Linq2Entities 不支持调用表达式。
对此有什么建议吗?
谢谢!
I want to do a method with a signature like this:
Expression<Func<TSource, bool>> CreatePropertyFilter<TSource>(Expression<Func<TSource, string>> selector, string value, TextMatchMode matchMode);
Basically, it takes a property selector (ex: p = p.Name
), a string value and a enum value that can be StartsWith
, EndsWith
, Contains
, Exact
; for text matching options.
How can I implement the method in a way that LINQ2Entities can understand? I already implemented the method using nested invocation expressions like this:
Expression<Func<string, bool>> comparerExpression;
switch (matchMode)
{
case TextMatchMode.StartsWith:
comparerExpression = p => p.StartsWith(value);
break;
case TextMatchMode.EndsWith:
comparerExpression = p => p.EndsWith(value);
break;
case TextMatchMode.Contains:
comparerExpression = p => p.Contains(value);
break;
default:
comparerExpression = p => p.Equals(value);
break;
}
var equalityComparerParameter = Expression.Parameter(typeof(IncomingMail), null);
var equalityComparerExpression = Expression.Invoke(comparerExpression, Expression.Invoke(selector, equalityComparerParameter));
var equalityComparerPredicate = Expression.Lambda<Func<IncomingMail, bool>>(equalityComparerExpression, equalityComparerParameter);
The problem is that Linq2Entities doesn't support Invocation expressions.
Any advice on this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
本质上,给定一个选择器:
您当前正在构造一个谓词表达式,例如:
相反,使用其主体(a
MemberExpression
)“扩展”选择器表达式,以构造一些东西就像:这看起来像:
翻译方法是:
Essentially, given a selector:
You are currently constructing a predicate expression like:
Instead, 'expand' out the selector expression by using its body (a
MemberExpression
), to construct something like:This would look like:
Where the translating method is: