2

In entity framework, i know that you can set a property as virtual to get it too lazy load, which is great. But in my service code i would like to load a list of children, and also a list in each of those children.

Instead of getting entity framework to load this data, i can load the data in 2 hits.

Here is an example, of my classes

public class Parent
{
    public long Id { get; set; }

    public virtual ICollection<Child> Children { get; set; }
}

public class Child
{
    public long Id { get; set; }

    public long ParentId { get; set; }

    public ICollection<GrandChild> { get; set; }
}

public class GrandChild
{
    public long Id { get; set; }

    public long ChildId { get; set; }

    public virtual AnotherClass AnotherProperty { get; set; }
}

In my service code i am loading the data like this, as i cant see to be able to load all of them at once (maybe i just dont know the correct query syntax)

var parent = await _context.Parents
    .Where(e => e.Id == 9)
    .Include(e => e.Children)
    .FirstOrDefaultAsync();

var grandchildren = await _context.GrandChildrens
    .Where(e => e.Child.ParentId == 9)
    .ToListAsync();

// this is load again?
foreach (var child in parent.Children)
    child.GrandChildren = (from a in grandChildren where a.ChildId == child.Id).ToList();

Now everytime i am trying to set child.GrandChildren, entity framework is trying to load the data. How can i stop it loading the data, but without removing the virtual keyword, as in other instances, i would like entity framework to lazy load.

Also, if anyone knows how to load parent, child, grandchildren in 1 query, please let me know too

Gillardo
  • 9,518
  • 18
  • 73
  • 141
  • If you want all entities to be loaded at once, you should load them eagerly then. – kamil-mrzyglod Sep 23 '15 at 08:51
  • In this case, that is what i am trying to do, but entity framework is trying to load them, when i am setting the property. If i let Entity Framework load the lists, it would cause 3 connections, where as if i do it, i can do it in 2. This is a sample, on larger objects i can load the data in far less connections then entity framework – Gillardo Sep 23 '15 at 08:53
  • have you read: http://stackoverflow.com/questions/13047845/how-to-include-a-child-objects-child-object-in-entity-framework-5 – tschmit007 Sep 23 '15 at 08:58
  • You shouldn't be concerned about connections since ADO uses connection pooling. – kamil-mrzyglod Sep 29 '15 at 05:03

1 Answers1

0

I think you can load related entities eagerly like following:

var parent = await _context.Parents
    .Where(e => e.Id == 9)
    .Include(e => e.Children.GrandChildrens)
    .FirstOrDefaultAsync();

This should load parents, their children and their grand children.

kamil-mrzyglod
  • 4,948
  • 1
  • 20
  • 29