Entity Framework 4: convert string condition to lambda expression?

I want to accept an array of strings where conditions from the client are similar to field == value . It would be very useful to create a specification object that could take a 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" into
DB.Products.Where(p => p.name == "JujyFruits") ?

+8
c # entity-framework-4
source share
3 answers

you can use

  • Reflection to get Product.name property from name string and
  • LINQ Expression 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 (divide by spaces, parse the operator and select the appropriate expression instead of 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: since Func<T, TResult> sealed, you cannot extract from it. However, you can create an implicit conversion operator that translates Specification<T> to Func<T, bool> .

+14
source share

We recently opened the Dynamic LINQ library from VS2008 sample projects. Works great to turn Where string expressions into expressions.

This link will lead you there.

+3
source share

You need to include the search query in the predicate. Try the following:

 string searchString = "JujyFruits"; Func<Product, bool> search = new Func<Product,bool>(p => p.name == searchString); return DB.Products.Where(search); 
0
source share

All Articles