2012-02-21 53 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(); 

您现在应该能够在查询中执行连接。

我还没有测试过,所以它可能无法按预期工作。