I am trying to create Linq Expression that I can use to query child entity for parent properties(PATIENT entity in this case), using this method:
private IQueryable<LAB_ORDER> SelectFilter(string fieldName, string value)
{
var param = Expression.Parameter(typeof(PATIENT), "item");
var field = Expression.PropertyOrField(param, fieldName);
var search = Expression.Constant(value, typeof(string));
var body = Expression.Call(field, "Contains", null, search);
Expression<Func<LAB_ORDER, bool>> lambda;
if (String.IsNullOrEmpty(value))
{
lambda = x => true;
}
else
{
lambda = Expression.Lambda<Func<LAB_ORDER, bool>>(body, parm);
}
var linqFilter = from e in context.LAB_ORDERS select e;
return linqFilter.Where(lambda);
}
Looks like it builds an expression correctly, but exception I am getting is this:
System.ArgumentException: ParameterExpression of type 'PATIENT' cannot be used for delegate parameter of type LAB_ORDER'.
While I can do linqFilter.Where( x => x.PATIENT.LAST_NAME == "Smith") without any problems, can't use expression above, which should translate to something similar to this. How would I fix the expression above to correct it? I am eagerly loading parent entity with a child so that's not a problem.
EDIT
From Anders reply it looks like I need to modify lambda expression to:
lambda = Expression.Lambda<Func<PATIENT, bool>>(body, parm);
Now when I try to use it, linqFilter.Where(lambda) gives me compile error "No suitable overload" which I understand why - linqFilter is
"IQueryable<LAB_ORDER>", not "IQueryable<PATIENT>",
so how should I do that?
Just to sum things up, the only question remains - how to create Expression for parent properties?