2012-02-21 49 views
0

我有實體框架的設置,我有以下關係設置:負載EF關係加入

  • AdListing(AdListingID,標題,詳細信息)
  • AdListingLocation(安AdListing可以有多個位置:AdListingID, LocationID)
  • 位置(LocationID,國家,市)

在EF我想返回所有AdListings所在城市爲 「紐約」

請注意我還想加載AdListingLocation關係(以及其他一些關係)。在另一篇文章中,我瞭解到,如果我正在使用,我不允許進行手動連接。包括。我怎樣才能完成這兩個?

var results = (from a in db.AdListings.Include("AdListingPhotos").Include("AdListingLocations") 
       where a.AdListingLocations.Location.City = "New York" 
       select a).ToList(); 
+0

你的意思是通過人工加入?其中a.AdListingLocations.Location.City ==「紐約」不是真正的手動連接。查詢將創建一個連接,但您只是導航關係。 – Dismissile 2012-02-21 19:04:06

回答

1
var results = from a in db.AdListings 
       where a.AdListingLocations.Location.City == "New York" 
       select a; 

return results 
     .Include(a => a.AdListingPhotos) 
     .Include(a => a.AdListingLocations) 
     .ToList(); 

要獲得包括只是把此行的lambda語法:

using System.Data.Entity; 
+0

當我嘗試了你的建議,我得到的錯誤: 'System.Linq.IQueryable '不包含'Include'的定義並且沒有擴展方法'Include'接受類型' System.Linq.IQueryable '可以找到(你是否缺少使用指令或程序集引用?) – TheWebGuy 2012-02-21 19:07:54

+0

您是否添加了使用System.Data.Entity? – Dismissile 2012-02-21 20:17:47

+0

是的,我包括你指定的使用語句,我檢查了System.Data.Entity及其使用版本「4.0.0.0」和運行時版本「v4.0.30319」的版本,你認爲我需要更高版本嗎? – TheWebGuy 2012-02-21 21:46:43

0

您是否嘗試過在查詢後移動.Include()調用?

var results = (from a in db.AdListings 
      where a.AdListingLocations.Location.City = "New York" 
      select a).Include("AdListingPhotos").Include("AdListingLocations").ToList(); 

您現在應該能夠在查詢中執行連接。

我還沒有測試過,所以它可能無法按預期工作。