I'm doing a search form that has a few different options and have it all working except this one part.
For reference I'm posting the entire method but the issue I'm having is trying to do a dynamic expression to check a bool? property.
This line of code is where I'm having the problem...
call = Expression.IsTrue(propertyAccess); //TODO: Check if the property is true
As written it complains about bool to bool? conversion. If I change it to a bool instead of bool? it complains that IsTrue is not a valid Linq expression.
Basically I want to do x => x.UltrasonicTest == true but don't know how to set that to a MethodCallExpression.
Here is the short version of the code...
public ActionResult Search(List<string> selectedTests)
{
IQueryable<Logbook> logbooks;
Expression lambdaStatus = null;
Expression lambdaTests = null;
Expression lambdaFinal = null;
ParameterExpression parameter = Expression.Parameter(typeof(Logbook), "logbook");
Expression call = null;
PropertyInfo property = null;
property = typeof(Logbook).GetProperty("UltrasonicTest");
if (property != null)
{
MemberExpression propertyAccess = Expression.MakeMemberAccess(parameter, property);
call = Expression.IsTrue(propertyAccess); //TODO: Check if the property is true
lambdaTests = call;
}
lambdaFinal = Expression.And(lambdaStatus, lambdaTests);
Expression<Func<Logbook, bool>> predicate = Expression.Lambda<Func<Logbook, bool>>(lambdaFinal, parameter);
logbooks = db.Logbooks.Where(predicate);
List<Logbook> filteredLogbooks = logbooks.OrderByDescending(x => x.DateEntered.Value).Take(50).ToList();
return View("Index", filteredLogbooks);
}
Rather than attempting to create a MethodCallExpression try constructing a BinaryExpression with the right as a Constant of true.
Something like this:
call = Expression.MakeBinary(ExpressionType.Equal, propertyAccess, Expression.Constant(true, typeof(bool?)));
Edit
Or tidier option:
call = Expression.Equal(propertyAccess, Expression.Constant(true, typeof(bool?)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With