4

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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
LaundroMatt
  • 2,158
  • 1
  • 19
  • 20

3 Answers3

8

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;
Andrei Andrushkevich
  • 9,905
  • 4
  • 31
  • 42
  • the null error was caused by the either the ScreenName, FirstName or the LastName being null. Putting in user.ScreenName != null and surrounding it and the Contains filter with brackets ( ) did the trick. Thanks. – LaundroMatt Apr 24 '11 at 05:23
2
IEnumerable<User> users = from user in databaseUsers
where
     (user.ScreenName + ' ' + user.FirstName + ' ' + user.LastName).Contains(search)
select user;
lfnaves
  • 29
  • 2
0

Either your user is a null entry, or your databaseUsers are not initialized.

Jake Kalstad
  • 2,045
  • 14
  • 20