When IQueryable returns no record ToList() throws an exception

江枫思渺然 提交于 2019-12-07 12:39:21

问题


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?


回答1:


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?




回答2:


try to use this code

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



回答3:


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; }
}


来源:https://stackoverflow.com/questions/4465242/when-iqueryable-returns-no-record-tolist-throws-an-exception

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