Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 611
TriFatlete Avatar asked Nov 13 '08 17:11

TriFatlete


1 Answers

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();
like image 69
BigJoe714 Avatar answered Oct 05 '22 20:10

BigJoe714