使用 EF 并在事务中包装条件块时,只要将 DbContext 传递到块内的方法中,它会继承启动的事务吗?
示例,DbContext 作为最后一个参数传递到方法中:
var db = new DbContext();
if(action == "Remove")
{
using (var tran = db.Database.BeginTransaction()
{
try
{
MyMethod(param1, param2, db);
//do some more things to another db table
db.SaveChanges();
tran.Commit();
}
catch
{
tran.Rollback();
}
}
return;
}
该方法还包含 SaveChanges():
public static void MyMethod(int param1, string param2, DbContext db)
{
try
{
//do some table updates
db.SaveChanges();
}
catch
{
//throw exception
}
}
所以,我假设如果该方法由于某种原因失败,那么整个事务都会回滚?并且,如果该方法成功,但该方法外部(但仍在事务内部)所做的更改失败,那么该方法所做的更改也会回滚吗?
EF 指南中未记录这种特殊情况,因此我们将不胜感激。
你是对的。当您将 Context 传递给方法时,您就拥有了事务
if(action == "Remove")
{
using (var db = new DB_Context())
{
using (var tran = db.Database.BeginTransaction()
{
try
{
MyMethod(param1, param2, db);
//do some more things to another db table
db.SaveChanges();
tran.Commit();
}
catch
{
tran.Rollback(); //It is not required. Using(...) {...} will automatically call Dispose()
}
}
}
return;
}
public static void MyMethod(int param1, string param2, DbContext db)
{
try
{
//do some table updates
db.SaveChanges();
}
catch
{
throw;
}
}