fubo
fubo

Reputation: 45947

Entity Framework Transaction handling

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

Answers (1)

Eivind T
Eivind T

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

Related Questions