Reputation: 45947
I have the following code:
MyEntities myNewObject = new MyEntities();
MyEntities2 myNewObject2 = new MyEntities2();
using (var context = new MyContext())
{
context.MyEntities.AddObject(myNewObject);
context.SaveChanges(); //saves myNewObject
myNewObject2.MyEntitiesID = myNewObject.Id;
context.MyEntities2.AddObject(myNewObject2);
context.SaveChanges(); //saves myNewObject2 with ID of myNewObject
}
Now I would like to handle this as a transaction. If the insert of myNewObject2 fails, myNewObject is already in the database. There is no reference between these objects in the database.
Upvotes: 0
Views: 117
Reputation: 1059
SaveChanges will save both your changes in a transaction if you omit the first SaveChanges().
Antoher option is use a transactionscope
using (var trans = new TransactionScope())
using (var context = new MyContext())
{
//...do operations
trans.Complete();
}
Upvotes: 1