Asp.net mvc 执行联接时加载EF关系

Asp.net mvc 执行联接时加载EF关系,asp.net-mvc,entity-framework,Asp.net Mvc,Entity Framework,我有实体框架设置,我有以下关系设置: AdListing(AdListingID、标题、详细信息) AdListingLocation(一个AdListing可以有多个位置:AdListingID、LocationID) 位置(位置ID、国家/地区、城市) 在EF中,我想返回城市为“纽约”的所有广告列表 请记住,我还想加载AdListingLocation关系(以及其他一些关系)。在另一篇博文中,我了解到,如果我使用.Include,就不允许进行手动连接。我怎样才能做到这两个呢 var re

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

  • AdListing(AdListingID、标题、详细信息)
  • AdListingLocation(一个AdListing可以有多个位置:AdListingID、LocationID)
  • 位置(位置ID、国家/地区、城市)
在EF中,我想返回城市为“纽约”的所有广告列表

请记住,我还想加载AdListingLocation关系(以及其他一些关系)。在另一篇博文中,我了解到,如果我使用.Include,就不允许进行手动连接。我怎样才能做到这两个呢

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

您是否尝试在查询后移动
.Include()
调用

var results = (from a in db.AdListings
           where a.AdListingLocations.Location.City = "New York"
           select a).Include("AdListingPhotos").Include("AdListingLocations").ToList();
您现在应该能够在查询中执行联接

我还没有测试过这个,所以它可能不会像预期的那样工作

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;

你说的手动连接是什么意思?其中a.AdListingLocations.Location.City==“纽约”实际上不是手动加入。该查询将创建联接,但您只是在浏览关系。当我尝试您的建议时,出现错误:“System.Linq.IQueryable”不包含“Include”的定义,并且找不到扩展方法“Include”接受类型为“System.Linq.IQueryable”的第一个参数(是否缺少using指令或程序集引用?)是否添加了using System.Data.Entity?是的,我包括了您指定的using语句,检查了System.Data.Entity的版本及其using版本“4.0.0.0”和运行时版本“v4.0.30319”您认为我需要更高版本吗?它可能已在4.1中添加。您可以将代码更改为使用字符串版本。我喜欢lambda语法,因为如果指定无效的关系,它将在编译时失败。