Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contains Query on multiple columns

How do I search multiple columns using LINQ to SQL when any one of the column could be null?

IEnumerable<User> users = from user in databaseUsers
        where
             user.ScreenName.Contains(search)
             || user.FirstName.Contains(search)
             || user.LastName.Contains(search)
        select user;

I keep getting this exception:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

like image 872
LaundroMatt Avatar asked Dec 27 '22 21:12

LaundroMatt


2 Answers

add not null condition user.Property != null

  IEnumerable<User> users = from user in databaseUsers
    where
         (user.ScreenName != null && user.ScreenName.Contains(search))
         || (user.FirstName != null && user.FirstName.Contains(search))
         || ( user.LastName != null && user.LastName.Contains(search))
    select user;
like image 93
Andrei Andrushkevich Avatar answered Dec 30 '22 11:12

Andrei Andrushkevich


IEnumerable<User> users = from user in databaseUsers
where
     (user.ScreenName + ' ' + user.FirstName + ' ' + user.LastName).Contains(search)
select user;
like image 42
lfnaves Avatar answered Dec 30 '22 11:12

lfnaves