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>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With