简体   繁体   中英

Entity Framework: Query is slow

I am having some problems with Entity Framework. I have simplified this to make it easier to explain.

These are my mssql tables mssql表

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM