Shaul Behr
Shaul Behr

Reputation: 38033

How to soft-code a Linq/EF query

I want to write a generic extension method that will return a specified set of objects, according to a user-defined filter, with a signature like so:

public static IEnumerable<T> GetObjects<T>(this ObjectSet<T> os, string fieldName, object value) where T : EntityObject {}

Of course, we could change the signature to handle multiple filters, but let's first focus on the single field filter.

How would you write a Linq query that does this?

Upvotes: 3

Views: 181

Answers (1)

tukaef
tukaef

Reputation: 9214

You need to dynamically build lambda-expression and call Queryable.Where for os with this expression:

public static IQueryable<T> GetObjects<T>(this ObjectSet<T> os, 
                                          string fieldName, object value)
{
    var param = Expression.Parameter(typeof(T), "x");
    var body = Expression.Equal(
        Expression.PropertyOrField(param, fieldName), 
        Expression.Constant(value, value.GetType()));
    var lambda = Expression.Lambda<Func<T, bool>>(body, param);
    return os.Where(lambda);
}

Upvotes: 6

Related Questions