I\'m triying to make a function that add a \'where\' clause to a query based in a property and a value. This is a very simplefied version of my function.
Pri
You need to convert the code to an expression tree.
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace WindowsFormsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
using (var context = new NorthwindEntities())
{
IQueryable query = context.Customers;
query = Simplified(query, "CustomerID", "ALFKI");
var list = query.ToList();
}
}
static IQueryable Simplified(IQueryable query, string propertyName, string propertyValue)
{
PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName);
return Simplified(query, propertyInfo, propertyValue);
}
static IQueryable Simplified(IQueryable query, PropertyInfo propertyInfo, string propertyValue)
{
ParameterExpression e = Expression.Parameter(typeof(T), "e");
MemberExpression m = Expression.MakeMemberAccess(e, propertyInfo);
ConstantExpression c = Expression.Constant(propertyValue, propertyValue.GetType());
BinaryExpression b = Expression.Equal(m, c);
Expression> lambda = Expression.Lambda>(b, e);
return query.Where(lambda);
}
}
}