0

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.

Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
fubo
  • 44,811
  • 17
  • 103
  • 137
  • Please review this [question](http://stackoverflow.com/questions/815586/entity-framework-using-transactions-or-savechangesfalse-and-acceptallchanges) and its answers. – HuorSwords May 02 '14 at 08:13

1 Answers1

1

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();
}
Eivind T
  • 1,059
  • 9
  • 14
  • Are you sure that SaveChanges() will save with a transaction? I was not aware of that! – BenjaminPaul May 02 '14 at 08:19
  • 1
    Yes (http://msdn.microsoft.com/en-us/library/dn456843.aspx - "In all versions of Entity Framework, whenever you execute SaveChanges() to insert, update or delete on the database the framework will wrap that operation in a transaction.") – Eivind T May 02 '14 at 08:22
  • Is there nothing on myContext to perform what @fubo wants? Using TransactionScope looks odd to me. – gsharp May 02 '14 at 08:37
  • 2
    You can create your own transaction with context.Database.BeginTransaction() – Eivind T May 02 '14 at 08:47