Linq Expression to handle null

强颜欢笑 提交于 2019-12-24 12:26:35

问题


I am trying to use the following code in a linq expression, which I found at this question However it fails if the database field is null.

  public static IQueryable<T> FieldsAreEqualOrBothNullOrEmpty<T>(
        this IQueryable<T> source,
        Expression<Func<T, string>> member,
        string value)
    {
        Expression body;
        if (string.IsNullOrEmpty(value))
        {
            body = Expression.Call(typeof(string), "IsNullOrEmpty", null, member.Body);
        }
        else
        {
            body = Expression.Equal(
                Expression.Call(member.Body, "ToLower", null),
                Expression.Constant(value.ToLower(), typeof(string)));
        }
        return source.Where(Expression.Lambda<Func<T, bool>>(body, member.Parameters));
    }

It looks to me as if the code

 Expression.Call(member.Body, "ToLower", null)

is the problem , but I don't know what to use in it's place.


回答1:


Expression.Call(member.Body, "ToLower", null)

should be replaced with

Expression.IfThenElse(
    Expression.Equal(member.Body, Expression.Constant(null)),
    Expression.Constant(null),
    Expression.Call(member.Body, "ToLower", null))

which translates to

body == null ? null : body.ToLower();


来源:https://stackoverflow.com/questions/33315584/linq-expression-to-handle-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!