0

I need to create a db "task" where all steps have to complete successfully, or the entire thing rolls back. Is this possible?

e.g.

public ActionResult Create()
{
        // Get list of current season pass holders
        var seasonPasses = db.SeasonPasses;

        // Create a new game
        var game = new Game { Description = "Next Game", RegistrationOpen = Convert.ToDateTime("09/08/2014"), RegistrationClose = Convert.ToDateTime("09/12/2014") };
        db.Games.Add(game);

        if (db.SaveChanges() > 0)
        {
            foreach (var pass in seasonPasses)
            {
                // Create new reservations for all the season pass holders
                var res = new Reservation { Game = game, SpaceNumber = pass.SpaceNumber, User = pass.User };
                db.Reservations.Add(res);
            }

            // If every season pass holder received a new reservation
            if (db.SaveChanges() == seasonPasses.Count())
            {
                // Show success message
                return View("SuccessMessage");
            }
        }


        // If ANYTHING fails...

        /******************************************
         * Roll Everything Back To The Way it Was *
         *     \/ Then Show Failure Message \/    *
         * ****************************************/

        return View("FailureMessage");
 }
drewwyatt
  • 5,989
  • 15
  • 60
  • 106
  • 5
    What you're looking for is called [Transaction scopes](http://msdn.microsoft.com/fr-fr/library/system.transactions.transactionscope(v=vs.110).aspx). – Florian F. Sep 04 '14 at 15:02
  • 5
    @FlorianF.: And here is the [**English Version**](http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope(v=vs.110).aspx) :) – Nope Sep 04 '14 at 15:06
  • 3
    Or just stop calling `SaveChanges` constantly. You can build an entire object graph with Entity Framework before finally calling `SaveChanges` and not incur multiple connections. – Chris Pratt Sep 04 '14 at 15:49

1 Answers1

0

You can use transactions like:

var transaction = _context.Database.BeginTransaction();

//Doing some operations with your context.

transaction.Commit();
transaction.Rollback();

During transaction you can use SaveChanges() method, but changes will not apply to database before calling method Commit() for transaction.

Artyom Rusak
  • 27
  • 1
  • 5