1

I've got three classes that look like the following. I'll call them Parent, Child and Grandchild.

public class Parent 
{
  public int Id {get;set;}
  public string Name {get;set;}
  public virtual List<Child> Children {get;set;}
  public virtual List<Grandchild> Grandchildren {get;set;}
}

public class Child 
{
  public int Id {get;set;}
  public string Name {get;set;}
  public virtual Parent Parent {get;set;}
  public virtual List<Grandchild> Grandchildren {get;set;}
}

public class Grandchild 
{
  public int Id {get;set;}
  public string Name {get;set;}
  public virtual Parent Parent {get;set;}
  public virtual Child Child {get;set;}
}

Now, I use a repository pattern with EF6. For the grab method for a parent, I have something like the following:

public List<Parent> GrabParent(Expression<Func<Parent, bool>> predicate) 
{
  return _context.Parents
    .Include(a => a.Children)
    .Include(a => a.Grandchildren)
    .Where(predicate)
    .ToList();
}

I use a similar method to grab the grandchild records:

public List<Grandchild> GrabGrandchildren(Expression<Func<Grandchild, bool>> predicate)
{
  return _context.Grandchildren
    .Include(a => a.Parent)
    .Include(a => a.Child)
    .Where(predicate)
    .ToList();
}

Now, if I were to call the GrabParent method, I would receive a list of Parents and a list of each of the Children. However, I wouldn't be able to access any of the Grandchildren records, despite their being relationally linked to each of the Children records that I am able to access.

Similarly, if I call the GrabGrandchildren method, I'll be able to retrieve a list of the Grandchildren and information about the Child, but I wouldn't be able to get any information about the Parent.

Why is this and how can I go about retrieving that additional related information?

Whit Waldo
  • 4,806
  • 4
  • 48
  • 70

1 Answers1

2

See EF code-first: How to load related data (parent-child-grandchild)? for an explanation.

Essentially, I would modify the GrabGrandchildren method to the following:

public List<Grandchild> GrabGrandchildren(Expression<Func<Grandchild, bool>> predicate) 
{
  return _context.Grandchildren
    .Include(a => a.Child)
    .Include(a => a.Child.Select(b => b.Parent)
    .ToList();
}
Community
  • 1
  • 1
Whit Waldo
  • 4,806
  • 4
  • 48
  • 70