简体   繁体   中英

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.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM