Using EF 2.0 Core, code first, I have the following entity which defines a self-referencing table:
class EntityX
{
public int EntityXId { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
//navigation properties
public EntityX Parent { get; set; }
public ICollection<EntityX> Children { get; set; }
}
I want to retrieve all EntityX objects and their children in the form of a 'tree'
I can do that using:
var entities = context.EntityX
.Include(p => p.Parent)
.Include(p => p.Children)
.Where(p => p.Parent == null);
When I call entities.ToList()
this gets me what I want: a list of parent
entities with their children edit only 'first' generation children. When I omit the Where()
clause, I get all entities and their children.
I do not understand why the Where()
clause works. Objects that are part of the Children
collection have a Parent
. Why are they not omitted?
Edit: my question was answered but please be aware that I was wrong in my perception of how Include() works.