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 :-








Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm