Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code First CTP5, using Include method with Many to Many table

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

like image 573
Yoo Matsuo Avatar asked Mar 09 '11 14:03

Yoo Matsuo


1 Answers

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.

like image 159
Ladislav Mrnka Avatar answered Nov 09 '22 22:11

Ladislav Mrnka