简体   繁体   中英

C# Null check in expression trees

I have a class called User in which there is a field wherein the user can send any data type. Currently we are sending int, double and string.

Since the field is dynamic meaning the field name could be anything we are using expression trees. The issue I am facing now is if the field is null in the select query or the field value then it throws error.

Below is my code:

Expression<Func<User, bool>> comparison = null;

if (Value.GetType() == typeof(int))
    comparison = EvaluateRules<int>(attributeName);
else if (Value.GetType() == typeof(double))
    comparison = EvaluateRules<double>(attributeName);
else if (Value.GetType() == typeof(string))
    comparison = EvaluateRules<string>(attributeName);


private Expression<Func<User, bool>> EvaluateRules<T>(string attributeName)
{
    var attributeParameter = Expression.Parameter(typeof(User), "user");
    Expression<Func<User, bool>> comparison = null;
    var parseMethod = typeof(T).GetMethod("Parse", new[] { typeof(string) });

    switch (policyOperator)
    {
        case Operator.GreaterThanOrEqual:
            if (Value.GetType() != typeof(string))
                comparison = Expression.Lambda<Func<User, bool>>(
                                    Expression.GreaterThanOrEqual(
                                        Expression.Call(parseMethod, Expression.Property(attributeParameter, attributeName)),
                                        Expression.Constant(Value)),
                                        attributeParameter);
            break;
    }

    return comparison;
}

resultUsers = from user in users.AsQueryable().Where(comparison) select user

Any clues??

Thanks for your time.

Thanks for your reply. I was able to solve it with the below code. Posting it in case it helps someone.

ParameterExpression attributeParameter = Expression.Parameter(typeof(User), "user");
MemberExpression attribute = Expression.Property(attributeParameter, attributeName);
BinaryExpression nullCheck = Expression.NotEqual(attribute, Expression.Constant(null, typeof(object)));
BinaryExpression condition = null;

 switch (policyOperator)
{
    case Operator.GreaterThanOrEqual:
    if (Value.GetType() != typeof(string))
        condition = Expression.GreaterThanOrEqual(Expression.Call(parseMethod, 
                        Expression.Property(attributeParameter, attributeName)), 
                            Expression.Constant(Value));

    .
    .
}

return Expression.Lambda<Func<User, bool>>(Expression.AndAlso(nullCheck, condition), attributeParameter);                           

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM