Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Dynamic Where Clause

I have a query like:

var function = GetSomeExpression();    

using (FooModel context = new FooModel())
{
    var bar = context.Bar.Where(function);
}

I'd like to make a generic method that can execute Where against different Entities in the context. The goal is not having to do context.Bar.Where, context.Car.Where, Context.Far.Where, etc.

Something that cannot be done, but illustrates the goal is:

var q = context.GetObjectContext(T).Where(queryFunction);

I have looked into using Relfection and can get the Where method, but do not know how to execute it against the context passing in the delegate. I also looked at DynamicMethod, but doing the whole IL thing does not like appealing.

What I have so far:

private List<T> GetResults<T>(Expression<Func<T, bool>> queryFunction)
{
    // note: first() is for prototype, should compare param type
    MethodInfo whereMethod = typeof(Queryable).GetMethods()
        .Where(m => m.Name == "Where")
        .First().MakeGenericMethod(typeof(T)); 

    // invoke the method and return the results
    List<T> result = whereMethod.Invoke(
    // have the method info
    // have the expression
    // can reference the context 
    );

    throw new NotImplementedException();
}

Is this possible to do?

like image 831
blu Avatar asked Feb 10 '09 19:02

blu


1 Answers

This is way easier then what I was trying before:

private List<T> GetResults<T>(IQueryable<T> source, 
    Expression<Func<T, bool>> queryFunction)
{
   return source.Where(queryFunction).ToList<T>();
}
like image 87
blu Avatar answered Sep 24 '22 17:09

blu