[英]Entity Framework 4: convert a string condition to a lambda expression?
I want to accept a string array of where conditions from the client like field == value
.我想接受来自客户端的 where 条件的字符串数组,例如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.创建一个可以接受构造函数中的字符串的规范 object 和 output 一个 lambda 表达式来表示 Where 子句会非常好。 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"
into你怎么能把"name == Jujyfruits"
变成DB.Products.Where(p => p.name == "JujyFruits")
? DB.Products.Where(p => p.name == "JujyFruits")
?
You can use您可以使用
Product.name
from the string name
and从字符串name
中获取属性Product.name
的反射和Expression
class to manually create a lambda expression. LINQ Expression
class 手动创建 lambda 表达式。 Note that the following code example will only work for Equals (==)
operations.请注意,以下代码示例仅适用于Equals (==)
操作。 However, it is easy to generalize to other operations as well (split on whitespace, parse the operator and choose the appropriate Expression instead of Expression.Equal
).但是,它也很容易推广到其他操作(按空格分割,解析运算符并选择适当的 Expression 而不是Expression.Equal
)。
var condition = "name == Jujyfruits";
// Parse the condition
var c = condition.Split(new string[] { "==" }, StringSplitOptions.None);
var propertyName = c[0].Trim();
var value = c[1].Trim();
// Create the lambda
var arg = Expression.Parameter(typeof(Product), "p");
var property = typeof(Product).GetProperty(propertyName);
var comparison = Expression.Equal(
Expression.MakeMemberAccess(arg, property),
Expression.Constant(value));
var lambda = Expression.Lambda<Func<Product, bool>>(comparison, arg).Compile();
// Test
var prod1 = new Product() { name = "Test" };
var prod2 = new Product() { name = "Jujyfruits" };
Console.WriteLine(lambda(prod1)); // outputs False
Console.WriteLine(lambda(prod2)); // outputs True
About the constructor thing: Since Func<T, TResult>
is sealed, you cannot derive from it.关于构造函数:由于Func<T, TResult>
是密封的,因此您不能从中派生。 However, you could create an implicit conversion operator that translates Specification<T>
into Func<T, bool>
.但是,您可以创建一个隐式转换运算符,将Specification<T>
转换为Func<T, bool>
。
We've recently discovered the Dynamic LINQ library from the VS2008 sample projects.我们最近从 VS2008 示例项目中发现了 Dynamic LINQ 库。 Works perfectly to turn string based "Where" clauses into expressions.完美地将基于字符串的“Where”子句转换为表达式。
You need to turn your search term into a predicate.你需要把你的搜索词变成一个谓词。 Try something like the following:尝试以下操作:
string searchString = "JujyFruits";
Func<Product, bool> search = new Func<Product,bool>(p => p.name == searchString);
return DB.Products.Where(search);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.