John
John

Reputation: 17471

Entity Framework 6: Associating a 'Child' Collection

Let's say I have a table that looks like so:

Person
{
   int Id,
   string Name,
   int? ParentId
}

In entity framework, I can add a new property Person Parent and I can tell entity framework how that should be mapped:

HasOptional(a => a.Parent).WithMany().HasForeignKey(c => c.ParentId);

My question is, is there a way in this scenario to add this:

ICollection<Person> Children { get; set; }

Where the collection would be populated with all Person rows having a ParentId of this current Person?

Upvotes: 0

Views: 72

Answers (1)

JotaBe
JotaBe

Reputation: 39014

Add a property for your children, like this:

public ICollection<Person> { get; set; }

Then configure the mapping like this:

HasMany(p => p.Children).WithOptional(p => p.Parent);

Then you simply have to access the Children property using lazy loading, eager loading (Include(p => p.Children) or explicit loading.

If you don't have the navigation property is still possible to do it, but less obvious.

MyContext.Person.Where(p => p.ParentId = parentId);

Upvotes: 1

Related Questions