Mori
Mori

Reputation: 2574

Getting the modifed entities in OpenAccessContext in case on an Exception

I know we can have access to the new/modified/deleted entities in OpenAccessContext by the following commands.

dbContext.GetChanges().GetInserts<object>() dbContext.GetChanges().GetUpdates<object>() dbContext.GetChanges().GetDeletes<object>()

If an execption occures for any reasons while perfoming SaveChanges(), I need to log those entities but they get cleared in case of exceptions.

Is there anyway to get the entities out of OpenAccessContext in case on exceptions?

Upvotes: 0

Views: 67

Answers (1)

Lextendo
Lextendo

Reputation: 33

You could override the SaveChanges method like this:

  public override void SaveChanges()
  {
    ContextChanges cruds = this.GetChanges;
    IList<object> inserts = cruds.GetInserts<object>();
    IList<object> updates = cruds.GetUpdates<object>();
    IList<object> deletes = cruds.GetDeletes<object>();

    try {
        base.SaveChanges(ConcurrencyConflictsProcessingMode.AggregateAll);
    } catch (Exception ex) {
        // Retry or in your case log...
        this.Refresh(RefreshMode.PreserveChanges, updates); 
        this.Delete(deletes);
        this.Add(inserts);

        Thread.Sleep(1000);
        base.SaveChanges();
    } finally {
        this.FlushChanges(true);
    }
  }

When the savechanges failed, the changes are still accessible. You could also log the exception while you are at it.

Upvotes: 1

Related Questions