Anjali Iyengar
Anjali Iyengar

Reputation: 350

Re-use transaction when saveChanges() fail + EF

What would within-transaction db state and transaction-state be in case context.savechanges() fails. Can I reuse the same transaction but create a new context?

// Should the retry be at this level in case saveChanges() fail.
    using(var transaction = new TransactionScope())
    {
    // retry at this level in case saveChanges() fail. Use the ambient transaction?
      using(var context = new DbContext)
      {
      //do some update and encounter exception (e.g., concurrency exception.)
      context.saveChanges();
      }
    transaction.Complete();
    }

Upvotes: 0

Views: 249

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89201

What would within-transaction db state and transaction-state be in case context.savechanges() fails. Can I reuse the same transaction but create a new context?

The exact behavior is provider-specific and error-specific. But the generic answer is that a failure may doom the entire transaction, or even the DbContext, so you cannot retry after arbitrary failures in the transaction.

It may work for concurrency exceptions, or other specific failures, but you'd need to test and handle those as special cases.

Upvotes: 1

Related Questions