2012-02-17 60 views
0

我拉出我的頭髮,我不知道爲什麼我不能返回AdPhotos和位置實體。我使用.ToList()不應該保持AdPhotos集合完好?Eager loading在EF無法正常工作

當我把一個斷點上的回報,我可以看到AdPhotos和位置數據,但之後消失。

public List<AdListing> LatestAdListings() 
{ 
    using (var db = new AdultdirectoryEntities()) 
    { 
     var results = (from a in db.AdListings.Include("AdPhotos").Include("Location") 
         join l in db.Locations on a.LocationID equals l.LocationID 
         where a.Approved && l.CountryID == Constants.ItemKeys.UsCountryId && a.AdPhotos.Count > 0 
         orderby a.CreateDateTime descending 
         select a).Take(5).ToList(); 

     return results; 
    } 
} 
+0

在此頁面(http://msdn.microsoft.com/en-us/library/bb896272.aspx)我讀過「當您調用Include時,查詢路徑只對返回的ObjectQuery實例有效,其他ObjectQuery實例和對象上下文本身不受影響。」 我認爲這是我的問題,有沒有人有更好的解決方案來返回完整的關係? – TheWebGuy 2012-02-17 23:17:11

回答

1

您的Include調用之後是手動連接 - 不支持。一旦使用手動連接或投影,您正在更改查詢的形狀,並且所有呼叫都將丟失。

而且你不需要加入,因爲你可以編寫查詢:

var results = (from a in db.AdListings.Include("AdPhotos").Include("Location") 
       where a.Approved && a.Location.CountryID == Constants.ItemKeys.UsCountryId && a.AdPhotos.Count > 0 
       orderby a.CreateDateTime descending 
       select a).Take(5).ToList(); 
+0

謝謝!這有幫助。我還有一個問題。如果id喜歡在「位置」關係中處理另一個關係,那麼我該如何執行此操作? – TheWebGuy 2012-02-21 16:40:51