2013-07-24 28 views
1

我有一個Rack模型和一個服務器模型。目前,當我想找回單個服務器我這樣做,指定明確的加載: -如何在lambda表達式中指定包含

public Server FindAllServer(int id) 
     { 

      return project.Servers.Where(c => c.ServerID == id) 
       .Include(a => a.OperatingSystem) 
       .Include(a2 => a2.DataCenter) 
       .Include(a3=>a3.Rack) 
       .Include(a4=>a4.ServerModel) 
       .Include(a5=>a5.Technology) 
       .Include(a6=>a6.VirtualMachines) 
       .Include(a7=>a7.TechnologyStatu) 
       .Include(a8=>a8.TechnologyBackUpStatu) 
       .Include(a9=>a9.TechnologyRole) 
       .SingleOrDefault(); 
     } 

但現在我要顯示一個機架及其所有服務器/ S,我做了以下內容: -

public Rack FindAllRack(int id) 
     { 

      return project.Racks.Where(c => c.RackID == id) 
       .Include(a => a.Servers) 
       .Include(a2 => a2.DataCenter) 
       .Include(a3 => a3.Firewalls) 
       .Include(a4 => a4.Routers) 
       .Include(a5 => a5.Technology) 
       .Include(a6 => a6.StorageDevices) 
       .Include(a7=>a7.Switches) 
       .Include(a8=>a8.Zone) 
       .SingleOrDefault(); 
     } 

,所以我不知道我怎麼可以定義明確包括機架下的所有的服務器/ s的導航性能,如我不能寫的東西: -

project.Racks.Where(c => c.RackID == id).Include(a => a.Servers.Include(………)) 

的問題是,在情況我h在一個機架下有50個服務器,然後每個服務器會有大約7個請求來檢索服務器導航屬性,所以我將有大約350個請求!

+0

如果您有可能是您的父對象的子集合,那麼您可能需要對SQL進行配置文件以確保您的數據庫在生產級卷的負載下保持不變。我已經看到這種查詢在開發中很好,然後網格停止生產。你確定你確實需要所有的兒童記錄嗎? –

+0

是的,我需要所有的孩子記錄。 –

+0

我包括所有這些兒童記錄,因爲在主機架頁面上,我將顯示有多少服務器,交換機等與此機架相關聯。所以如果我不包括這些導航屬性,它將導致一個問題,因爲單獨的請求來檢索每個導航屬性的計數將被髮送。 –

回答

0

你試過嗎?

return project.Servers 
       .Include(a => a.OperatingSystem) 
       .Include(a2 => a2.DataCenter) 
       .Include(a3=>a3.Rack) 
       .Include(a4=>a4.ServerModel) 
       .Include(a5=>a5.Technology) 
       .Include(a6=>a6.VirtualMachines) 
       .Include(a7=>a7.TechnologyStatu) 
       .Include(a8=>a8.TechnologyBackUpStatu) 
       .Include(a9=>a9.TechnologyRole) 
       .Where(srv => srv.Rack.RackID == id); 
1

我想你應該能夠與Include()基於字符串的超載做到這一點通過指定屬性路徑,例如

project.Racks.Where(c => c.RackID == id).Include("Servers.SomePropertyOfServer") 

編輯:做一些進一步的研究之後,看來這也可能工作:

project.Racks.Where(c => c.RackID == id).Include(a => a.Servers.Select(s => s.SomePropertyOfServer))

this link,特別是標題爲「熱切加載多個級別」的一個例子。

+0

所以這樣我需要重新編寫服務器的整個包含列表,在Rack的包含列表中。 –

+0

看起來如此。您也可以將您想要的屬性投影爲匿名類型。 – luksan

1

如果您需要的只是各種子對象的計數,請考慮以下內容。它應該向數據庫發出一個請求,最多隻能讀取2行。對請求進行剖析,以確保這種情況屬實,因爲我沒有對其進行測試。

 return project.Racks.Where(c => c.RackID == id) 
      .Select(a => new { 
       serverCount = a.Servers.Count(), 
       dataCenterCount = a.DataCenter.Count(), 
       firewallCount = a.Firewalls.Count(), 
       routerCount = a.Routers.Count(), 
       technologyCount = a.Technology.Count(), 
       storageDeviceCount = a.StorageDevices.Count(), 
       switchCount = a.Switches.Count(), 
       zoneCount = a.Zone.Count() 
      }).SingleOrDefault(); 

此外,如果您不打算在拋出異常時拋出多條記錄,請使用FirstOrDefault而不是SingleOrDefault。