Include method with Many to Many table in EF Code First CTP5

ef-code-first entity-framework linq-to-entities

Question

I have something like the following many to many relationship tables.

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; }
}

and, get shops information.

using (var context = new DataContext())
{
 return context.Shops.Include(s => s.ShopFacilities)
                     .Include("ShopFacilities.Facility")  // This line
                     .First(x => x.Id == id);
}

What I want to do is call the Include method with a Lambda expression for a many to many relationship instead of string. I've tried to implement like the below code:

using (var context = new DataContext())
{
 return context.Shops.Include(s => s.ShopFacilities)
                     .Include(s => s.ShopFacilities.Facility)  // Cannot compile
                     .First(x => x.Id == id);
}

But as you guess I cannot compile it. Actually, the first code snippet works well, so basically it's okay, though, I'm kinda curious whether there is a work around or not.

Any help would be appreciated,

Yoo

1
6
3/9/2011 2:47:00 PM

Accepted Answer

Try this:

return context.Shops.Include(s => s.ShopFacilities.Select(f => f.Facility))
              .First(x => x.Id == id);     

But you should follow what @Kristof suggested in comment.

16
3/9/2011 2:45:00 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow