Linq表达式处理null [英] Linq Expression to handle null

查看:614
本文介绍了Linq表达式处理null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在linq表达式中使用以下代码,我发现在
这个问题
但是如果数据库字段为空,则它失败。

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));
    }

看起来好像代码

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

是问题,但我不知道该怎么用。

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

推荐答案

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

应该替换为

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

其中翻译为

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

这篇关于Linq表达式处理null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆