Check if there is a bool? True in dynamic lambda

I am making a search form that has several different options and everything works except for this one part.

For reference, I am posting the whole method, but the problem I am facing is trying to make a dynamic expression to check a property bool?

.

This line of code is where I have the problem ...

call = Expression.IsTrue(propertyAccess); //TODO: Check if the property is true

      

As written, it complains about converting bool

to bool?

. If I change it to bool

instead 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 it to MethodCallExpression

.

Here is a 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);
    }

      

+3


source to share


2 answers


Instead of trying to create MethodCallExpression

, try to create BinaryExpression

with the right true

.

Something like that:

call = Expression.MakeBinary(ExpressionType.Equal, propertyAccess, Expression.Constant(true, typeof(bool?)));

      



Edit

Or a neater option:

call = Expression.Equal(propertyAccess, Expression.Constant(true, typeof(bool?)));

      

+1


source


If UltrasonicTest

is bool?

, you have to decide what value should be returned if it is null. If you just want to lambda Do not null property returned , and - true, you can create the following expression:

x => x.UltrasonicTest.GetValueOrDefault()

      



Assuming I want to create this expression from scratch, here's how I would do it:

var param = new ParameterExpression(typeof(Logbook), "x");
var prop = Expression.PropertyOrField(param, "UltraSonicTest");
var valOrDefault = Expression.Call(prop, "GetValueOrDefault", null);

var lambda = Expression.Lambda<Func<LogBook, bool>>(valOrDefault, param);

      

+1


source







All Articles