简体   繁体   English

实体框架交易处理

[英]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. 如果myNewObject2的插入失败,则myNewObject已在数据库中。 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(). 如果您省略第一个SaveChanges(),则SaveChanges会将您的所有更改都保存在事务中。

Antoher option is use a transactionscope 另一个选择是使用transactionscope

using (var trans = new TransactionScope())
using (var context = new MyContext())
{
  //...do operations
  trans.Complete();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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