I am new to dynamic expression query. I want to create a join query dynamically. Below it the query for which I want the equivalent dynamic query:
var lstNums = new List<int> { 100, 101 };
var getAll = new StudentRepository().GetAll(); // returns IQueryable<Student>
var query = getAll.Join(lstNums, a => a.StudentId, b => b, (a, b) => a).ToList();
- The
lstNumscan be list of any primitive data types - The
getAllcontainsIQueryable<Student>, this can beIQueryable<T>of any entity - The
querywill contain theList<Student>records after doing join with thegetAlland list of integers. But the result can be any list of entity. The list i.e. lstNum can be any list of primitive data types.
This is what I have tried:
public static IQueryable JoinQuery(this IQueryable outer, IEnumerable innerEntities, string firstEntityPropName,
Type typeSecondEntity, Type typeResultEntity, params object[] values)
{
LambdaExpression outerSelectorLambda = DynamicLinq.DynamicExpression.ParseLambda(outer.ElementType, null, firstEntityPropName, values);
ParameterExpression expnInput = Expression.Parameter(typeSecondEntity, "inner");
ParameterExpression expnResult = Expression.Parameter(typeResultEntity, "outer");
return outer.Provider.CreateQuery(
Expression.Call(
typeof(Queryable), "Join",
new Type[] { outer.ElementType, innerEntities.AsQueryable().ElementType, outerSelectorLambda.Body.Type, expnResult.Type },
outer.Expression, innerEntities.AsQueryable().Expression, Expression.Quote(outerSelectorLambda), expnInput,
expnResult));
}
The extension method:
public static IQueryable<T> JoinQuery<T>(this IQueryable outer, IEnumerable innerEntities, string firstEntityPropName, Type typeSecondEntity, Type typeResultEntity, params object[] values)
{
return (IQueryable<T>)Extensions.JoinQuery((IQueryable)outer, (IEnumerable)innerEntities, firstEntityPropName, typeSecondEntity, typeResultEntity, values);
}
Note: I have installed System.Linq.Dynamic nuget package version 1.0.7 for dynamic linq expression.