I am writing a method that generates some EFCore Linq code using Linq expressions for a specific filtering API. It will write some statements like:
dbContext.Student
.Where(s => s.Address.ZipCode == 10005)
.Intersect(dbContext.Student
.Where(s => s.FirstName == "John")
For that I need get the MethodInfo of the Where and of the Intersect methods.
I tried using GetMethod on the type but it returns null (not working on extension methods):
MethodInfo method = typeof(Queryable).GetMethod("Where",
BindingFlags.Public | BindingFlags.Static,
null,
CallingConventions.Any,
new[] { typeof(IQueryable<Student>),
typeof(Expression<Func<Student, bool>>)},
null);
I also tried the following:
MethodInfo method = typeof(Queryable)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(mi => mi.Name == "Where");
// TO DO : taking the first of where Methods is bad.
.First()
.MakeGenericMethod(typeof(DbSet<Student>));
But I get a badArgument0 when used on DbSet.
Any clue of the class where I can find the right Where DbSet extension ?
You do not need MethodInfo
here, you can create just call expression:
var queryable = dbContext.Student.AsQueryable();
var lambda = ...
var whereCall = Expression.Call(typeof(Queryable),
nameof(Queryable.Where),
new[] { typeof(Student) },
queryable.Expression,
lambda
);
// and final
return queryable.Provider.CreateQuery<Student>(whereCall);