How to use transactions with a datacontext

前端 未结 5 1501
清歌不尽
清歌不尽 2020-12-08 21:49

Can I use transactions with a datacontext, so that I can rollback the state of the context after an error? And if so, how does that work?

5条回答
  •  没有蜡笔的小新
    2020-12-08 22:36

    It's not as simple as the TransactionScope method but, as I understand it, this is the "correct" way to do it for LINQ-to-SQL. It doesn't require any reference to System.Transactions.

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

    Of course, the RollBack is only required if you intend to do further data operations within the using, otherwise changes will be automatically discarded.

提交回复
热议问题