Contains Query on multiple columns

时光总嘲笑我的痴心妄想 提交于 2019-12-22 08:37:07

问题


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.


回答1:


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;



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/5757364/contains-query-on-multiple-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!