Doozie
Doozie

Reputation: 39

When IQueryable returns no record ToList() throws an exception

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

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

What is the solution?

Upvotes: 3

Views: 7006

Answers (3)

Derek Greer
Derek Greer

Reputation: 16282

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

Upvotes: 1

Andrei Andrushkevich
Andrei Andrushkevich

Reputation: 9973

try to use this code

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

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1503130

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?

Upvotes: 5

Related Questions