Take the 2-minute tour ×

Im looking for a pattern which I can use for parent-child relationships when inserting records into a database. As the child record needs the parent record to exist first, Im having to use nasty things like storing the session id then updating the foreign key after saving the parent record.

Are there any well know patterns to solve this problem. Regards Gareth

share|improve this question
Are you calling a stored proc or inserting/updating directly? What do you mean by 'session id'? Are the parent and child saved at the same time? Which foreign key are you referring to? –  Adam Ralph Nov 3 '09 at 17:27

2 Answers 2

You seem to be either recording children before or at the same time as their parents, which is possible but kind of odd. Your data model suggests children know about their parents, therefore, the data suggest a parent to be inserted before its children. You may not achieve this in a single query since the foreign key you're talking about is referring to the same table (A.parent -> A.id).

share|improve this answer

It sounds like you are not using a framework like NHibernate or Hibernate and you are rolling your own which is fine, but you may want to look at an existing OR mapping framework if you have this option. If you are rolling your own and you need to do linked inserts then you would do these using transactions in your repository, so as an example:

public class ParentRepository
    public void Save(Parent parent)
        using (TransactionScope scope = new TransactionScope())
           //Add you database code here to insert to both tables in a transaction
share|improve this answer
+1 for NHibernate but I don't think how TransactionScope will help, so -1 for that –  zvolkov Nov 3 '09 at 18:03
TransactionScope helps because if you have an object hierarchy where you have a parent object that contains a child object and you are inserting a new record you are wanting to ensure data integrity. Performing this in a transaction will ensure that when you insert the parent and the child fails then the transaction will rollback and the integrity of your database is maintained. –  Michael Mann Nov 3 '09 at 18:38

Your Answer


