Reputation: 3827
I am having some problems with Entity Framework. I have simplified this to make it easier to explain.
These are my mssql tables
I use the following code to get all cities for each of the countries in my MSSQL database
var country = new Country()
{
Cities = obj.Counties.SelectMany(e => e.Cities).Select(city => new DCCity
{
Name = city.Name,
Population = city.Population
})
};
This is returned as json
There is a bit more then 40.000 records in the city table. To retrieve a list with all the countries and their respective cities it takes around 8 seconds. I am trying to reduce this. Anyone know some optimization tips to achieve this?
Upvotes: 1
Views: 178
Reputation: 9319
You need to query the Cities table first to get all data:
var cities = _context.Cities.Select(x => new {
ContryId = x.County.Country.CountryId,
ContryName = x.County.Country.Name,
CityId = x.Id,
CityName = x.Name
});
var countryLookup = new Dictionary<int, CountryDto>(approximatelyCountOfCountries);
foreach (var city in cities)
{
CountryDto country;
if (!countryLookup.TryGetValue(city.CountryId, out country))
{
country = new CountryDto {
Name = city.CountryName,
Id = city.CountryId
Cities = new List<CityDto>(approximatelyCountOfCities)
};
countryLookup.Add(country.Id, country);
}
country.Cities.Add(new CityDto { Name = city.Name, Id = city.Id });
}
In this way the result will be the:
countryLookup.Values
Upvotes: 1
Reputation: 2880
Try to do somthing like this:
var result = from c in countries
join conty in counties on c.id equals conty.CountryId
join city in cities on conty.id equals city.CountyId
group city by c.Name into g
select new
{
Name = g.Key,
Cities = g.Select(x =>
new
{
x.Name,
x.Population
})
};
Upvotes: 0