2014-10-17 72 views
1

我遇到了一些實體框架問題。 我簡化了這一點,使其更容易解釋。實體框架:查詢很慢

這些都是我的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秒。我正試圖減少這一點。任何人都知道一些優化技巧來實現這一點?

+0

請發表您的完整代碼。您提供的代碼段不會生成該輸出。 – James 2014-10-17 18:46:00

+0

使用SQL Server事件探查器查看發送到數據庫服務器的SQL。 – Dai 2014-10-17 18:46:39

+0

你真的需要所有40k記錄嗎? – DavidG 2014-10-17 18:47:39

回答

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 
+0

這解決了我的問題! – reachify 2014-10-18 00:30:22

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