如何使用datacontext进行事务处理

时间:2009-05-15 08:56:00

标签: c# linq linq-to-sql transactions datacontext

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

5 个答案:

答案 0 :(得分:18)

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

try
{
  dc.Connection.Open();
  dc.Transaction = dc.Connection.BeginTransaction();

  dc.SubmitChanges();
}
finally
{
  dc.Transaction.Rollback();
}

<强>更新

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

答案 1 :(得分:15)

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

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

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

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(),则将回滚事务。如果存在包含事务范围,那么内部和外部事务都需要完成才能提交要提交的数据库的更改。

答案 2 :(得分:12)

它不像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,否则将自动丢弃更改。

答案 3 :(得分:10)

这样的事情,可能是:

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
}

答案 4 :(得分:0)

是这样的:

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();
   }
}