Insert into multiple database tables using Linq, ASP.NET MVC

asp.net-mvc, linq-to-sql

Solution

Do you have the relationship defined between the 2 tables in the object relational designed? If so, you can have linq take care of assigning the ID property of the second table automatically.

Example... Table A – Order OrderId OrderDate Table B – Order Item OrderItemId OrderId ItemId

Code (Using LINQ-to-SQL):

Order order = new Order();
Order.OrderDate = DateTime.Now();
dataContext.InsertOnSubmit(order);

OrderItem item1 = new OrderItem();
Item1.ItemId = 123;
//Note: We set the Order property, which is an Order object
// We do not set the OrderId property
// LINQ will know to use the Id that is assigned from the order above
Item1.Order = order;  
dataContext.InsertOnSubmit(item1);

dataContext.SubmitChanges();

Problem

I have a rather simple scenario where I have two tables in which I want to add data. They are managed with primary key/foreign key. I want to add new data into TABLE A and then retrieve the Id and insert into TABLE B. I can certainly do it with a stored procedure, but I'm looking at trying to do it using Linq. What is the best approach ? I can certainly get the ID and do two separate inserts but that doesn't certainly seem to be a very good way of doing things. ``` db.Table.InsertOnSubmit(dbObject); db.SubmitChanges(); Int32 id = dbOject.Id; //Rest of the code ``` Any way to elegantly do this?

Original source