2

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.

Community
  • 1
  • 1
Kirsten
  • 15,730
  • 41
  • 179
  • 318

1 Answers1

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

should be replaced with

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

which translates to

body == null ? null : body.ToLower();
Akash Kava
  • 39,066
  • 20
  • 121
  • 167
  • I get Argument type bool is not assignable to parameter type 'system.linq.Expressions.Expression' – Kirsten Oct 24 '15 at 08:58
  • Should it be Expression.Equal not Expression.Equals ? – Kirsten Oct 24 '15 at 17:11
  • https://social.msdn.microsoft.com/Forums/en-US/d260f631-cf76-4c7a-8305-903faf7f373b/nullable-types-in-expression-build?forum=linqprojectgeneral has more information. – Kirsten Oct 24 '15 at 17:51