2012-02-17 27 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