Search code examples
c#.netlinqlambdaexpression-trees

Lambda expression weirdness in a LINQ to SQL 'where' condition


I am working on an ASP.NET MVC application which uses the repository pattern with LINQ to SQL as my data source. In my repository I expose the following method:

public IEnumerable<T> Find(Expression<Func<T, bool>> where)
{
    return _context.GetTable<T>().Where(where);
}

I am able to call this by saying:

repository<User>().Find(u => true);

But if I try doing (when search is null)

repository<User>().Find(u => !string.IsNullOrEmpty(search) ? u.UserName.Contains(search) : true);

I get the error:

Value cannot be null. Parameter name: text

I thought the lambda expression would execute the same thing since the value of search is null, but this is clearly not the case.

How do I fix this problem?


Solution

  • To add to the other answers, if you have to follow this ideal, you could simply do this instead:

    repository<User>.Find(u => string.IsNullOrEmpty(search) || 
                               u.UserName.Contains(search));
    

    Before blindly implementing this, if you were to do so, please read Adam's answer to learn of consequences.