I am new to Asp.Net Core and i am trying to build an API. I have the following model:
public class Location
{
public string Country { get; set; }
public string City { get; set; }
public string Street { get; set; }
}
I have populated my database and a country has multiple Cities and the City has multiple streets. I have created an End-point to return all the countries from the database:
[HttpGet("countries")]
public async Task<ActionResult<IEnumerable<string>>> GetCountries()
{
return await _context.Location.Select(x=>x.Country).Distinct().ToListAsync();
}
This is returning and Array of string and i want it to return a the following JSON format response:
[
{"country": "country1"},
{"country": "country2"},
..........
{"country": "countryN"}
]
My second end point is to retrieve all the cities from for a specific country :
[HttpGet("cities/{country}")]
public async Task<ActionResult<IEnumerable<string>>> GetCites(string country)
{
--------- Missing code ------
}
I have tried different options but i managed only to get array of string for both endpoints. I Have tried to replace the IEnumerable by IEnumerable, but without results.
CodePudding user response:
For the first api, create a model:
public class CountryResponse
{
public string Country { get; set; }
}
And use this model class in the return type of the API, and return the result as:
[HttpGet("countries")]
public async Task<ActionResult<IEnumerable<CountryResponse>>> GetCountries()
{
return await _context.Location.Select(x => new CountryResponse{ Country = x.Country }).Distinct().ToListAsync();
}
Similarly for the second API, create a response model:
public class CityResponse
{
public string City { get; set; }
}
And the API will look like
[HttpGet("cities/{country}")]
public async Task<ActionResult<IEnumerable<CityResponse>>> GetCites(string country)
{
return await _context.Location.Where(x => x.Country == country).Select(x => new CityResponse { City = x.City }).ToListAsync();
}
CodePudding user response:
The line
_context.Location.Select(x=>x.Country).Distinct().ToListAsync()
Returns a list of strings, so that is what the ActionResult will return. The easiest way to get it into the format you want is to return a KeyValuePair. If you changed the return to this, it should work.
return await _context.Location.Select.Distinct().Select(country => new KeyValuePair<string, string>("country", country)).ToList()
Same idea with the cities, just put them into a KeyValuePair and you should get what you need.