实体框架:查询很慢

时间:2014-10-17 18:39:15

标签: c# sql-server linq entity-framework optimization

我在使用Entity Framework时遇到了一些问题。 我简化了这一点,以便更容易解释。

这些是我的mssql表 mssql tables

我使用以下代码获取MSSQL数据库中每个国家/地区的所有城市

var country = new Country()
{
    Cities = obj.Counties.SelectMany(e => e.Cities).Select(city => new DCCity
    {
        Name = city.Name,
        Population = city.Population
    })
};

以json

的形式返回

enter image description here

城市表中有超过40.000条记录。要检索包含所有国家/地区及其各自城市的列表,大约需要8秒钟。我想减少这个。有人知道一些优化技巧来实现这个目标吗?

2 个答案:

答案 0 :(得分:1)

您需要首先查询Cities表以获取所有数据:

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

这样结果将是:

countryLookup.Values

答案 1 :(得分:0)

尝试做这样的事情:

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