实体框架事务处理
本文关键字:事务处理 框架 实体 | 更新日期: 2023-09-27 18:01:11
我有以下代码:
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
}
现在我想把它当作一笔交易来处理。如果插入myNewObject2失败,则myNewObject已在数据库中。数据库中的这些对象之间没有引用。
Antoher选项是使用交易范围
using (var trans = new TransactionScope())
using (var context = new MyContext())
{
//...do operations
trans.Complete();
}