6

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?

bendewey
  • 39,709
  • 13
  • 100
  • 125
blu
  • 12,905
  • 20
  • 70
  • 106
  • I had tried doing this a while back and ended up building a repository for each one. I'd like to know what other people think. The designer.cs generates a ctx.CreateQuery("[Bar]"); – bendewey Feb 10 '09 at 19:17

2 Answers2

7

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>();
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
blu
  • 12,905
  • 20
  • 70
  • 106
1

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.

Community
  • 1
  • 1
Michael G
  • 6,695
  • 2
  • 41
  • 59
  • No this helped. It made me realize I was doing way more then I needed to, thanks. – blu Feb 10 '09 at 20:29