When IQueryable returns no record ToList() throws

2019-05-16 02:43发布

dataContext.Geo_Countries.Where(c => c.Name.Contains(searchKey)).ToList();

when the IQueryable returns no records I get a value null exception.

What is the solution?

3条回答
乱世女痞
2楼-- · 2019-05-16 03:24

try to use this code

dataContext.Geo_Countries.Where(c => c.Name != null && c.Name.Contains(searchKey)).ToList();
查看更多
爷、活的狠高调
3楼-- · 2019-05-16 03:41

I suspect you don't get the problem when there are no matches - I suspect you get it when there's a row in your database with no Name value. Either that, or you're doing something else which you haven't shown us. What does the stack trace look like?

查看更多
够拽才男人
4楼-- · 2019-05-16 03:47

Calling ToList() on IQueryable will throw an exception if code doesn't properly execute. In the following example, ToList() will throw an exception if c.Name is null:

void Main()
{
    var countries = new [] { new Country() }.AsQueryable();
    countries.Where(c => c.Name.Contains("bubba")).ToList();
}


class Country{
  public string Name { get; set; }
}
查看更多
登录 后发表回答