Dynamic Where Clause in Entity Framework

c# entity-framework generics

Question

I would want to know:

var function = GetSomeExpression();    

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

I want to create a generic method that can be used to perform Where on various context-specific Entities. Not needing to consider context is the aim. Where the bar is, where the car is, how far it is, etc.

Despite being impossible, the following shows the objective:

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

I have looked at utilizing Relfection, and although I can get the Where method, I am unsure of how to use it with the delegate's context. I have looked into DynamicMethod, but using IL does not seem like much fun.

What I've got thus far is

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();
}

Can this be accomplished?

1
6
2/10/2009 8:19:39 PM

Accepted Answer

This is much simpler than what I was doing earlier:

private List<T> GetResults<T>(IQueryable<T> source, 
    Expression<Func<T, bool>> queryFunction)
{
   return source.Where(queryFunction).ToList<T>();
}
7
1/11/2010 7:40:55 PM

Popular Answer

view this article

Building where clauses in LINQ to entities to test collections in a many-to-many connection

After your post's update, this doesn't appear to be relevant anymore, but I'll keep it in case it's still useful. Edit



Related Questions





Related

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