【问题标题】:Entity Framework: Query is slow实体框架:查询很慢
【发布时间】:2014-12-13 09:53:56
【问题描述】:

我在使用实体框架时遇到了一些问题。 我已对此进行了简化,以便于解释。

这些是我的 mssql 表

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

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

这是以 json 格式返回的

city 表中有超过 40.000 条记录。要检索包含所有国家及其各自城市的列表,大约需要 8 秒。我正在努力减少这种情况。任何人都知道一些优化技巧来实现这一点?

【问题讨论】:

  • 请发布您的完整代码。您提供的 sn-p 不会产生该输出。
  • 使用 SQL Server Profiler 查看正在发送到数据库服务器的 SQL。
  • 您真的需要全部 40k 条记录吗?
  • 我假设您对每个国家的每个县进行单独查询
  • 您是否对每个国家/地区运行一个查询,而不是运行一个查询来获取所有数据? JSON在哪里出现,您是否将结果作为JSON发送到某个地方,是否可能需要很长时间而不是数据库查询?您如何创建 JSON,这可能是瓶颈吗?

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


【解决方案1】:

尝试做这样的事情:

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

【讨论】:

    【解决方案2】:

    需要先查询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
    

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-22
      相关资源
      最近更新 更多