tags:

views:

29

answers:

2

I'm using an MVC webform to insert a record into a database with several subrecords. In my code-behind I'm first creating a new main record using dataRepository.Add(xx). Now I need to add 5 subrecords that need the ID of the newly created record. How can I retrieve that?

A: 

You should probably submit all 5 records plus the main one all the way down to your datalayer, performing any validation on the way in your business layer. Then, depending on the implementation of your DL, save the main record, returning the ID, set the parent ID on the subrecords and save them. Do it all within a single transaction and you should be ok.

Please give more info on your data access layer.

If using MS SQL Server, you would use the Scope_Identity() within your stored procedure to get the last identity value inserted into an identity column. See this MSDN article

If using NHibernate you add them within the same session and NHibernate takes care of generating the SQL responsible for inserting the records with the correct Ids.

Daniel Dyson
A: 

If you are using an ORM such as Entity Framework you should be able to create the record and the associated records, link them by adding the associated records into a collection on the main object or setting them somehow and then call the save method on the context. This will do all the linking with ids etc. for you.

How are you doing data access?

WestDiscGolf