Lambda expression of strangeness in LINQ to SQL 'where' condition

I am working on an ASP.NET MVC application that uses a repository template with LINQ to SQL as a 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 can call it by saying:

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

But if I try to do (when the search is zero)

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

I get an error message:

The value cannot be null. Parameter Name: Text

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

How to fix this problem?

+3
source share
3 answers

, , :

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

, , , , .

+1

, ( ) . SQL, LINQ to SQL , null. LIKE null SQL, , LINQ to SQL null. , , .

, - string.Empty Contains. , , . .

+3

Contains a wait string. You have to get through string.Emtpy.

u.UserName.Contains(search)

If you try this, it will compile, but you will get a runtime error:

string str = "Leniel";

if (str.Contains(null))
{
    var num = 1;
}

Error:

Value cannot be null.
Parameter name: value
+1
source

Source: https://habr.com/ru/post/1756936/


All Articles