Entity framework core entity - self referential table

Say you have a self referencing table, that looks something like this (Root nodes points to null which signifies end of hierarchical organization.

We defined our Process model using code below :-

Next we need to tell EF our relationship

In the OnModelCreating method, use the following code to define relationship

modelBuilder.Entity().HasMany(p => p.SubNodes).WithOne(p => p.ParentNode).HasForeignKey(p => p.ParentId);

It basically says that we can have many SubNodes, one Parent node - which make sense right. We can have many parent.

Full code can be found here.

This code retrieve all the Process and its child (subnodes)

var result = p.Process.Include(a => a.SubNodes).Include(c => c.ProcessViewingHistory).AsNoTracking().ToList();
The code to pull out all, is show below :-


Popular posts from this blog

ionic2 cordova build android - Unable resolve gradle 2.2.3

A quick tutorial for OWASP ZAP tool for beginners

OpenCover code coverage for .Net Core