Where dynamic clause object structure

I have a query like:

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

I would like to create a general method that can execute Where with respect to different objects in the context. The goal is not to do context.Bar.Where, context.Car.Where, Context.Far.Where, etc.

Something that cannot be done but illustrates the purpose:

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

I have studied the use of Relfection and I can get the Where method, but I don’t know how to execute it against the context passing in the delegate. I also looked at DynamicMethod, but the execution of the entire IL file did not like.

What I still have:

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

+6
generics c # entity-framework
source share
2 answers

This is simpler than what I tried before:

 private List<T> GetResults<T>(IQueryable<T> source, Expression<Func<T, bool>> queryFunction) { return source.Where(queryFunction).ToList<T>(); } 
+7
source share

view this message

LINQ for Entities - Creating Suggestions for Testing Collections Between Many, Many

Edit : after updating your message, this no longer seems relevant; I will leave this in case this is useful.

+1
source share

All Articles