Ignore SqlTransaction.Commit within TransactionScope

前端 未结 1 1261
遇见更好的自我
遇见更好的自我 2021-01-18 07:41

We are in a process of gradually replacing legacy data access code by entity framework (4.3.1). In some occasions we can\'t avoid using both ways of data access in one unit

1条回答
  •  爱一瞬间的悲伤
    2021-01-18 07:48

    The update statement is still committed when scope.Complete() is not hit.

    Oh no!! The TransacationScope Is Not Being Used1.

    Auto-enlist only works if the Connection is open after (or inside) the TransactionScope.

    Putting the Open inside the TransactionScope should fix this issue (even with the manual transaction?) as the Connection will then [usually] auto-enlist in the ambient TS context.

    An existing connection can be enlisted into the ambient transaction scope: connection.EnlistTransaction(Transaction.Current).

    Alternatively, the TS can be created from an existing transaction, e.g. new TransactionScope(transaction), which may or may not be helpful here.

    Creating a manual transaction if perfectly fine, but TS (after the gotchas are figured out!) makes dealing with transactions simpler and easier .. at least in most cases :)

    Happy coding!


    1 The TS isn't being used for "the update statement". It will still [likely] be used for context.SaveChanges() as that will open a new connection which is then auto-enlisted.

    I have provided some options above, although I am unsure about the plain "nested" transaction. Seeing the (sealed?) API used in context might reveal more insights as to limitations/restrictions.

    0 讨论(0)
提交回复
热议问题