2

I am having trouble figuring out how to use .Include() to be able to access this nested relationship. I tried what seemed like the most direct way but intellisense doesn't populate and when I hand enter the relation there is a compilation error.

I have this db mapped setup

public class W
{
 public int WId { get; set; }
 public virtual ICollection<T> Ts { get; set; }
}

public class T
{
 public int TId { get; set; }
 public int WId { get; set; }
 public int CId { get; set; }
 public virtual W W { get; set; }
 public virtual C { get; set; }
}

public class C
{
 public int CId { get; set; }
 public virtual ICollection<T> Ts { get; set; }
}

I have a get method which queries

//set in constructor
DbSet<W> dbSet;
DbContext context;

//called in method
IQueryable<W> query = dbSet;
query = query.Include(w => w.Ts);//works
query = query.Include(w => w.Ts.C); //I wanted to do this but it doesn't work

Can I use .Include() like this?

It seemed like it was going to work with no hitch but apparently I am doing it wrong. I would prefer not to have to iterate through the Ts collection and then populate their C manually each time.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Travis J
  • 81,153
  • 41
  • 202
  • 273
  • BTW: Didn't you mean "nested" property instead of "inverse" in your question title? – Slauma May 07 '12 at 19:38
  • @Slauma - No, the virtual collection is considered an inverse property I thought. Class T holds the foreign key for W, and W holds a collection of T objects with that foreign key. I was under the impression this was considered an inverse property, and you can even explicitly label it with the data annotation which would apply here as `[InverseProperty("W")]` above W's definition for the Ts ICollection (although that would be redundant as EF will do this automatically if the Id's and foreign navigation names use the naming convention) – Travis J May 07 '12 at 19:44
  • The `W.T` collection is an inverse property of the `T.W` reference and the `T.W` reference is an inverse property of the `W.T` collection, it's "symmetric" somehow. Your question looks more like `W -> T -> C`, `C` "is nested" in `T` :) The answer would also apply if you remove `T.W` and `C.Ts`, then there is nothing inverse anymore. Anyway, forget my comment, I just thought it was a typo... – Slauma May 07 '12 at 19:55

1 Answers1

4

You can use this syntax:

query = query.Include(w => w.Ts.Select(t => t.C));
Slauma
  • 175,098
  • 59
  • 401
  • 420
  • Using this syntax I came across an issue of loading the wrong data. See here: http://stackoverflow.com/q/11676513/1026459 – Travis J Jul 26 '12 at 19:43