使用where子句的NullReferenceException

时间:2013-12-04 10:04:51

标签: c# linq linq-to-sql

我有一个场景,我正确地得到了结果。但我必须在那个结果中搜索它。这是我的代码。

if(productSearch.Keyword !=null || productSearch.Code!=null)
{
    var key = productSearch.Keyword;
    var cod = productSearch.Code;

    if (productSearch.Code != null)
    {
        var Selected_Result = result.Results.Where(s => s.Code.ToLower().Contains(cod.ToLower())).ToList();                     
        result.Results = Selected_Result;
    }
    else
    {
        var Selected_Result = result.Results.Where(s => s.Keyword.ToLower().Contains(key.ToLower())).ToList();                        
        result.Results = Selected_Result;
    }
}

但是它给出了以下例外:

  Object reference not set to an instance of an object

上的

result.Results.Where(s => s.Code.ToLower().Contains(cod.ToLower())).ToList();

我知道s => s.Code.ToLower()即将来临NULL,但我不知道为什么,result有记录。 提前谢谢。

1 个答案:

答案 0 :(得分:4)

如果查询中为null,那么数据库中的null可能就是{。}}。为了安全起见,您可以使用null coalescing运算符确保您至少某些来呼叫ToLower,例如。

result.Results.Where(s => (s.Code ?? "").ToLower().Contains(cod.ToLower()))
              .ToList();
相关问题