实体框架 4:将字符串条件转换为 lambda 表达式?
我想接受来自客户端的 where 条件的字符串数组,例如 field == value
。 如果创建一个规范对象,它可以接受构造函数中的字符串并输出 lambda 表达式来表示Where 子句,那就太好了。例如,我可以执行以下操作:
var myCondition = new Specification<Product>( myStringArrayOfConditions);
var myProducts = DB.Products.Where( myCondition);
您如何将 "name == Jujyfruits"
转换为DB.Products.Where(p => p.name == "JujyFruits “)?
I want to accept a string array of where conditions from the client like field == value
.
It would be really nice to create a specification object that could accept the string in the constructor and output a lambda expression to represent the Where clause. For example, I could do the following:
var myCondition = new Specification<Product>( myStringArrayOfConditions);
var myProducts = DB.Products.Where( myCondition);
How could you turn "name == Jujyfruits"
intoDB.Products.Where(p => p.name == "JujyFruits")
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
name
中获取属性Product.name
,并使用Expression
类来手动创建 lambda 表达式。请注意,以下代码示例仅适用于
Equals (==)
运算。然而,它也很容易推广到其他操作(按空格分割、解析运算符并选择适当的表达式而不是Expression.Equal
)。关于构造函数:由于
Func
是密封的,因此您无法从中派生。但是,您可以创建一个隐式转换运算符来转换Specification< ;T>
转换为Func
。You can use
Product.name
from the stringname
andExpression
class to manually create a lambda expression.Note that the following code example will only work for
Equals (==)
operations. However, it is easy to generalize to other operations as well (split on whitespace, parse the operator and choose the appropriate Expression instead ofExpression.Equal
).About the constructor thing: Since
Func<T, TResult>
is sealed, you cannot derive from it. However, you could create an implicit conversion operator that translatesSpecification<T>
intoFunc<T, bool>
.我们最近从 VS2008 示例项目中发现了动态 LINQ 库。非常适合将基于字符串的“Where”子句转换为表达式。
此链接将带您到达那里。
We've recently discovered the Dynamic LINQ library from the VS2008 sample projects. Works perfectly to turn string based "Where" clauses into expressions.
This link will get you there.
您需要将搜索词变成谓词。尝试如下操作:
You need to turn your search term into a predicate. Try something like the following: