Rollback additions / removals to DBSets of the DbContext using a transaction in Entity Framework

c# dbcontext entity-framework entity-framework-6

Question

For me, an everyday procedure in an Entity Framework 6 project is to

  1. Create new entities to be added.
  2. Include the entities in the relevantDBSet of theDbContext
  3. Set these objects' attributes
  4. Call DbContext.SaveChanges()

Pseudo-code for what I mean is as follows:

    // Psuedo code to illustrate process. 
    void AddProcess()
    {

        var modelsToAdd = GetModelsToAdd();

        try
        {
            _context.Models.AddRange(modelsToAdd);

            _context.SaveChanges();

            // If we get here all is good.
        }
        catch (Exception ex)
        {
            _context.RemoveRange(modelsToAdd);
            throw;
        }
        finally
        {
            //....
        }
    }

I understand theSaveChanges() internal creation of the techniqueTransaction so that if an error occurs during the saving, this will be undone. But what I really want is the removal of the additional entities in (2) from theDbSet If a mistake happens whileSaveChanges() . Basically, it will be as if the "Add" operation never happened.

As you can see, I am now keeping a list of the models involved in cache and eliminating them in the event of an exception.

I want to know if there is a better method to achieve this that Transactions can handle automatically. How therefore, can the internalTransaction reversal ofSaveChanges() also reverse any changes made to theDbSet 's? Alternative Transactions could also be utilised.

What is the most effective/preferred method to accomplish what I want? I may be missing something apparent since I'm still learning EF.

1
1
9/17/2018 10:12:29 PM

Accepted Answer

ZZZ_tmp
0
9/12/2018 6:26:07 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow