views:

157

answers:

1

I have a single page which collects related data into a series of input fields.

When the user clicks submit I want to insert the data into two different database tables in one go. ie I want to get the primary key from the first insert, and then use it for the second insert operation.

I am hoping to do this all in one go, but I am not sure of the best way to do this with the Models/Entities in MVC.

+1  A: 

Are you using LINQ or some other ORM? Typically these will support the ability to add a related entity and handle the foreign key relationships automatically. Typically, what I would do with LINQtoSQL is something like:

var modelA = new ModelA();
var modelB = new ModelB();

UpdateModel( modelA, new string[] { "aProp1", "aProp2", ... } );
UpdateModel( modelB, new string[] { "bProp1", "bProp2", ... } );

using (var context = new DBContext())
{
    modelA.ModelB = modelB;
    context.ModelA.InsertOnSubmit( modelA );
    context.SubmitChanges();
}

This will automatically handle the insertion of modelA and modelB and make sure that the primary key for modelA is set properly in the foreign key for modelB.

If you are doing it by hand, you may have to do it in three steps inside a transaction, first inserting modelA, getting the key from that insert and updating modelB, then inserting modelB with a's data.

EDIT: I've shown this using UpdateModel but you could also do it with model binding with the parameters to the method. This can be a little tricky with multiple models, requiring you have have separate prefixes and use the bind attribute to specify which form parameters go with which model.

tvanfosson
I am using DAAB with custom business objects. I have a feeling it could be tricky
Dkong