简体   繁体   English

如果在某些情况下不提交更改,是否需要手动回滚事务?

[英]Do I need to manually roll back a transaction if not committing changes given some conditions?

Example: Using transaction, and only committing if a given condition is satisfied. 示例:使用事务,并且仅在满足给定条件时提交。

using (var transaction = context.Database.BeginTransaction())
    // ...
    if (modelState.IsValid) {
        transaction.Commit();
    }
}

does it need to be: 是否需要是:

using (var transaction = context.Database.BeginTransaction())
    // ...
    if (modelState.IsValid) {
        transaction.Commit();
    } else {
        transaction.Rollback();
    }
}

or there is no need for the else part. 或不需要else部分。 What happens if I don't specify? 如果我不指定怎么办? Any good guidelines? 有什么好的指导方针吗?

You don't need to call Rollback manually because you are using the using statement. 您不需要手动调用回滚,因为您正在使用using语句。 It is not necessary to explicitly call Rollback . 不必显式调用Rollback The transaction will be rolled-back if Commit() has not been called. 如果尚未调用Commit()则事务将回滚。

DbContextTransaction.Dispose method will be called in the end of the using block. DbContextTransaction.Dispose方法将在using块的末尾调用。 And it will automatically rollback the transaction if the transaction is not successfully committed 如果未成功提交事务,它将自动回滚事务

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

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