3

I have the following models

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

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

public class GrandChild
{
    public int Id { get; set; }
    public string Name { get; set; }
}

What Im trying to do now is select a list of parents from the database with the children and grandchildren.

Tried the following with no joy:

List<Parent> parent = new List<Parent>();
parent = db.parent.ToList();
nemesv
  • 138,284
  • 16
  • 416
  • 359
Ernie
  • 49
  • 1
  • 9

2 Answers2

5

Use the Include method:

parent = db.parent.Include(parent => parent.Child.Select(child => child.GrandChild)).ToList();

For older versions of Entity Framework, you have to use a string instead of a lambda expression:

parent = db.parent.Include("Child.GrandChild").ToList();

Or you can use the custom Include extension method I blogged about here.

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • Get the following error Cannot convert lambda expression to type 'string' because it is not a delegate type – Ernie Jan 03 '14 at 14:14
  • @Ernie, you're probably using an older version of EF. See my updated answer. – Thomas Levesque Jan 03 '14 at 14:22
  • Been trying with lambda expressions for awhile and couldnt figure out why its not working. Thanks for the help. – Ernie Jan 03 '14 at 14:27
  • For EF Core, consider using the syntax from this answer http://stackoverflow.com/a/38741905/1047812 – Uriah Blatherwick Dec 14 '16 at 17:20
  • is the .Include syntax for Eager Loading a guarantee that EF will load the relationships? would be good to know the circumstances under which it will load vs when it may be merely a hint... I cannot find any doco stating either way. – joedotnot Jul 14 '18 at 00:31
0

in Linq to Sql you should use DataLoadOptions

var dlo = new DataLoadOptions();

dlo.LoadWith<Parent>(p => p.Child );
dlo.LoadWith<Child>(c=> c.GrandChild );
db.LoadOptions = dlo;

List<Parent> parent = new List<Parent>();
parent = db.parent.ToList();
Morten Anderson
  • 2,301
  • 15
  • 20