score:3

Accepted answer

Reflection isn't a problem here; EF won't even be able to notice the difference. The delegate approach is a non-starter, by the way (since you mention EF); ultimately, it is something like:

public static IQueryable<T> Where<T>(this IQueryable<T> query,
    string propertyName, object value)
{
    PropertyInfo prop = typeof(T).GetProperty(propertyName);
    var param = Expression.Parameter(typeof(T), "x");
    var body = Expression.Equal(
        Expression.Property(param, prop),
        Expression.Constant(value, prop.PropertyType)
        );
    var predicate = Expression.Lambda<Func<T, bool>>(body, param);
    return query.Where(predicate);
}

Note that you can make it easier with Expression.PropertyOrField(propertyName); the reason I haven't used that here is that it is very handy to know the member-type (prop.PropertyType) when creating the constant - otherwise you can get problems with nulls.

score:0

I know this an old answer but if someone see's this I've built this project:

https://github.com/PoweredSoft/DynamicLinq

Which should be downloadable on nuget as well:

https://www.nuget.org/packages/PoweredSoft.DynamicLinq

and you could simply do

query.Where("FirstName", ConditionOperators.Equal, "David");

Related Articles