我有类似以下多对多关系表。
public class Shop{
public int Id { get; set; }
public virtual ICollection<ShopFacility> ShopFacilities { get; set; }
}
public class ShopFacility
{
public int Id { get; set; }
public int ShopId { get; set; }
public int FacilityId { get; set; }
public virtual Shop Shop { get; set; }
public virtual Facility Facility { get; set; }
}
public class Facility
{
public int Id { get; set; }
public virtual ICollection<ShopFacility> ShopFacilities { get; set; }
}
并获取商店信息。
using (var context = new DataContext())
{
return context.Shops.Include(s => s.ShopFacilities)
.Include("ShopFacilities.Facility") // This line
.First(x => x.Id == id);
}
我想要做的是使用Lambda表达式调用Include方法以获得多对多关系而不是字符串。我试图像下面的代码那样实现:
using (var context = new DataContext())
{
return context.Shops.Include(s => s.ShopFacilities)
.Include(s => s.ShopFacilities.Facility) // Cannot compile
.First(x => x.Id == id);
}
但是你猜我无法编译它。实际上,第一个代码片段运行良好,所以基本上没关系,但是,我有点好奇是否有工作。
任何帮助将不胜感激,
柳
答案 0 :(得分:16)
试试这个:
return context.Shops.Include(s => s.ShopFacilities.Select(f => f.Facility))
.First(x => x.Id == id);
但你应该遵循@Kristof在评论中提出的建议。