How Do You Persist A Tree Structure To A Database Table With Auto Incrementing IDs Using An ADO.NET DataSet And A DataAdapter
I have a self-referential Role table that represents a tree structure
ID [INT] AUTO INCREMENT
Name [VARCHAR]
ParentID [INT]
I am using an ADO.NET DataTable and DataAdapter to load and save values to this table. This works if I only create children of existing rows. If I make a child row, then make a child of that child, then Update, the temporary ID value generated by the DataTable is going into the ParentID column. I have the following data relation set:
dataset.Relations.Add(New DataRelation("RoleToRole",RoleTable.Columns("ID"), RoleTable.Columns("ParentID")))
And when I make new child rows in the DataTable I call the SetParentRow method
newRow.SetParentRow(parentRow)
Is there something special I have to do to get the ID generation to propagate recursively when I call Update on the DataAdapter?
Answer
I don't know ADO.net in particular, but most ORMs won't automatically insert the ID of a new record in a relationship. You'll have to resort to the 2-step process:
- build and save parent
- build and save child with relationship to parent
The reason that this is difficult for ORMs is because you might have circular dependencies, and it wouldn't know which object it needed to create an ID for first. Some ORMs are smart enough to figure out those relationships where there are no such circular dependencies, but most aren't.
Related Questions
- → Function Undefined in Axios promise
- → React formatting dates with momentjs server side
- → Using ReactJs, How do I update my form fields when my parent object sent in from props changes?
- → Visual Studio 2012 Express: Browser returning 500 status trying to download jsx file
- → AngularJS directive: "templateUrl" doesn't work while "template" works
- → how to add cannonical tag for ASPX .NET page
- → Javascript Paypal slider string suffix
- → JavaScript in MVC 5 not being read?
- → Selecting an element by its attribute when it has a colon in its name
- → Function works for NON dynamically loaded images
- → URL routing requires /Home/Page?page=1 instead of /Home/Page/1
- → There are "gaps" between rows in my masonry cards
- → creating sef links and changing plus sign (+) with dash (-)