Dynamic Where Clause in Entity Framework

c# entity-framework generics


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")

    // 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?

2/10/2009 8:19:39 PM

Accepted Answer

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>();
1/11/2010 7:40:55 PM

Popular Answer

see this post

LINQ to entities - Building where clauses to test collections within a many to many relationship

Edit: after your post update this doesn't seem relevant anymore; I'll leave it in case it's helpful.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow