0

I'm having trouble figuring out why my code isn't working. When the field is empty, it just loads continuously. Also, when the field IS occupied adding something for the fourth time replicates the error. Any help?

private async Task<City> RetrieveCity(string name)
{
     // Instantiate return variable
     City city = null;

     // Find id in ProductLines table
     var cities = await db.Cities.Where(c => c.CityName.Equals(name)).ToListAsync();
     city = cities.First();

     return city;           
}
  • What do you mean by _field_? The parameter `name`? – Jan Köhler May 17 '16 at 08:26
  • Just add a Try-Catch block to your code and see what is kept in exception variable in debug mode. In 95% of all exceptions can be solved when developer can read and understand information contained in InnerException property. – Maciej S. May 17 '16 at 08:27

3 Answers3

2

As Maciej mentioned, it's very likely that you see the effect of loading continuously because an exception is thrown which isn't correctly caught and causes the UI to stay in the loading-state.

The error may occur because your query returns an empty list. Later on you invoke First() which raises that error if the list of cities is empty.

You could simplify your method like this:

private async Task<City> RetrieveCity(string name)
{
    return await db.Cities.FirstOrDefaultAsync(c => c.CityName.Equals(name));        
}
Jan Köhler
  • 5,817
  • 5
  • 26
  • 35
1

Make sure that the cities.Count()> 0 before you try to get the first element from the list.

private async Task<City> RetrieveCity(string name)
{
 // Instantiate return variable
 City city = null;

 // Find id in ProductLines table
 var cities = await db.Cities.Where(c => c.CityName.Equals(name)).ToListAsync();
 if(cities!=null && cities.Count()>0)
 { 
    city = cities.First();
 }   
 return city;           
}

Or simply you can fetch only only one using FirstOrDefault for your matching conditions like

private async Task<City> RetrieveCity(string name)
{
     var city = await db.Cities.FirstOrDefault(c => c.CityName.Equals(name));
     return city;           
}
error_handler
  • 1,191
  • 11
  • 19
0

Use

city = cities.FirstOrDefault();

It will return null if sequence is empty

More information :

https://msdn.microsoft.com/en-us/library/bb340482(v=vs.100).aspx

When to use .First and when to use .FirstOrDefault with LINQ?

Community
  • 1
  • 1
mohsen
  • 1,763
  • 3
  • 17
  • 55