How to use transactions with a datacontext

前端 未结 5 1498
清歌不尽
清歌不尽 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条回答
  •  旧时难觅i
    2020-12-08 22:33

    A DataContext will pick up an ambient transaction by default, so it is just a matter of ensuring there is a Transaction in scope. The details become the main issue:

    • What options do you need (e.g. isolation level)
    • Do you want a new transaction or reuse an existing transaction (e.g. an audit/logging operation might require a new transaction so it can be committed even if the overall business operation fails and thus the outer transaction is rolled back).

    This is simplified some prototype code, the real code uses helpers to create the transactions with policy driven options (one of the purposes of the prototype was to examine the impact of these options).

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

    If Complete() is not called then the transaction will be rolled back. If there is a containing transaction scope then both the inner and outer transactions need to Complete for the changes on the database to be committed.

提交回复
热议问题