Joe B
Joe B

Reputation: 788

Passing A DbSet<T> created at runtime via reflection to Queryable

I'm trying to execute a dynamic linq query where my DbSet Type is created at runtime via reflection an I'm getting the error:

"The best overloaded method match for 'System.Linq.Queryable.Where(System.Linq.IQueryable, System.Linq.Expressions.Expression>)' has some invalid arguments"

Here's my code

MyDataContext db = new MyDataContext ();
var dbType = db.GetType();
var dbSet = dbType.GetProperty("MyType").GetValue(db,null);
dbSet.GetType().InvokeMember("Local", BindingFlags.GetProperty, null, dbSet , null)
//just to show that it equal
dbSet.Equals(db.MyType); //returns true;
//here i create a dynamic expression tree 
dynamic l = Expression.Lambda(delagateType, greater, param);

//here it fails when i pass in my dbSet var but not when i pass db.MyType
dynamic q =   ((IEnumerable<object>)Queryable.Where(dbSet , l)).ToList();

Upvotes: 1

Views: 495

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205759

The problem is that your dynamic call contains two parameters, the first being static and the second being dynamic. In such case the compiler is using the static type information for the first argument, which is different - object when you pass dbSet variable and DbSet<MyType> when you pass db.MyType.

The trick is to hide the static type information from the compiler like this

dynamic q = ((IEnumerable<object>)Queryable.Where((dynamic)dbSet, l)).ToList();

Upvotes: 2

Related Questions