简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM