如何使用datacontext进行事务处理

我可以使用带有datacontext的事务,以便在出错后可以回滚上下文的状态吗? 如果是这样,那怎么办?

我一直在测试中使用它们:)

try { dc.Connection.Open(); dc.Transaction = dc.Connection.BeginTransaction(); dc.SubmitChanges(); } finally { dc.Transaction.Rollback(); } 

UPDATE

这将始终在事后回滚。 我在测试中使用它。

默认情况下,DataContext将选择环境事务,因此只需确保范围内存在事务。 细节成为主要问题:

  • 您需要什么选项(例如隔离级别)
  • 您是否需要新事务或重用现有事务(例如,审计/日志记录操作可能需要新事务,因此即使整个业务操作失败并因此回滚外部事务,也可以提交它。

这简化了一些原型代码,真正的代码使用帮助程序来创建具有策略驱动选项的事务(原型的目的之一是检查这些选项的影响)。

 using (var trans = new TransactionScope( TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }, EnterpriseServicesInteropOption.Automatic)) { // Perform operations using your DC, including submitting changes if (allOK) { trans.Complete(); } } 

如果未调用Complete(),则将回滚事务。 如果存在包含事务范围,则内部事务和外部事务都需要完成才能提交要提交的数据库的更改。

这样的事情,可能是:

 try { using (TransactionScope scope = new TransactionScope()) { //Do some stuff //Submit changes, use ConflictMode to specify what to do context.SubmitChanges(ConflictMode.ContinueOnConflict); scope.Complete(); } } catch (ChangeConflictException cce) { //Exception, as the scope was not completed it will rollback } 

它不像TransactionScope方法那么简单,但据我所知,这是为LINQ-to-SQL执行此操作的“正确”方法。 它不需要任何对System.Transactions的引用。

 dataContext.Connection.Open(); using (dataContext.Transaction = dataContext.Connection.BeginTransaction()) { dataContext.SubmitChanges(); if (allOK) { dataContext.Transaction.Commit(); } else { dataContext.Transaction.RollBack(); } } 

当然,只有在打算在使用中进行进一步的数据操作时才需要RollBack,否则将自动丢弃更改。

是这样的:

 using (YourDatacontext m_DB = new YourDatacontext()) using (TransactionScope tran = new TransactionScope()) { try { //make here the changes m_DB.SubmitChanges(); tran.Complete(); } catch (Exception ex) { Transaction.Current.Rollback(); } }