Linq with transaction
I have two tables : apartments and images, table image开发者_运维问答s has foreign key on table apartments. How to insert with LINQ ( C#) with transaction apartment and get that primary key ( apartment.id is auto increment ) so I can insert records in images in same transaction with real foreign key ?
Managing Id's? That's work for the ORM. Just do this - single transaction, all ids in place, no problem.
Apartment newApartment = new Apartment();
newApartment.Images.Add(new Image());
newApartment.Images.Add(new Image());
newApartment.Images.Add(new Image());
newApartment.Images.Add(new Image());
myDataContext.Apartments.Add(newApartment);
myDataContext.SubmitChanges();
Perform all your operations within an instance of TransactionScope
.
using(var ts = TransactionScope())
{
yourContext.SubmitChanges();
ts.Complete();
}
I'm not on my PC right now, so I'm not 100 % sure but it should be something like that.
Perform everything in a TransactionScope
:
using(var tx = new TransactionScope())
using(var db = new MyDataContext()) {
// query db, insert records, etc.
db.SubmitChanges();
tx.Complete();
}
Be aware that if you haven't already you will need to configure DTC. The instructions vary depending on your operating system (and it's not really a programming issue so I'll leave it at that).
精彩评论