执行连接时加载EF关系

时间:2012-02-21 18:48:51

标签: asp.net-mvc entity-framework

我有实体框架设置,我有以下关系设置:

  • AdListing(AdListingID,Title,Details)
  • AdListingLocation(AdListing可以有多个位置:AdListingID,LocationID)
  • 位置(LocationID,国家/地区,城市)

在EF中,我想返回City为“New York”的所有AdListings

请记住,我还想加载AdListingLocation关系(以及其他一些关系)。在另一篇文章中我了解到,如果我正在使用,我不允许手动连接.Include。我怎样才能完成两者?

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

2 个答案:

答案 0 :(得分: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();

要在Include上获取lambda语法,只需输入以下行:

 using System.Data.Entity;

答案 1 :(得分:0)

您是否尝试在查询后移动.Include()来电?

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

您现在应该可以在查询中执行联接。

我没有对此进行测试,因此可能无法按预期工作。