How to execute a transaction with the context of an Entity Framework object?

I created a very simple database using Entity Framework 4. I would like to be able to use transactions for entities, but I can't help but undo the changes. I really need a way to discard temporary changes to objects before they are saved to the database.

For example, the following code uses the context object object of the "MusicContainer" entity. Inside the TransactionScope, an Artist object is created. Then the transaction ends without completion; therefore, I expect the transaction to be canceled. But the program works as if I had never created a TransactionScope; after the TransactionScope completes, the music.SaveChanges () line stores the object in the database.

class Program
{
    static void Main(string[] args)
    {
        using (MusicContainer music = new MusicContainer())
        {
            using (TransactionScope transaction = new TransactionScope())
            {
                Artist artist = new Artist { Name = "Test" };
                music.Artists.AddObject(artist);
            }
            // The transaction ended without Complete(); shouldn't the changes be abandoned?
            music.SaveChanges();
        }
    }
}

TransactionScope , , , ? , MusicContainer, MusicContainer , (, , SaveChanges, MusicContainer).

+3
3

TransactionScope, SaveChanges() - , - using MusicContainer, using. TransactionScope , .

, , SaveChanges(). , . , :

        using (MusicContainer music = new MusicContainer())
        {
                Artist artist = new Artist { Name = "Test" };
                music.Artists.AddObject(artist);
                music.SaveChanges();
        }
+7

SaveChanges .

class Program
{
    static void Main(string[] args)
    {
        using (MusicContainer music = new MusicContainer())
        {
            using (TransactionScope transaction = new TransactionScope())
            {
                Artist artist = new Artist { Name = "Test" };
                music.Artists.AddObject(artist);
                music.SaveChanges();
            }
            // The transaction ended without Complete(); the changes are abandoned?
        }
    }
}

MusicContainer, .

+2

Entity structure should be able to use TransactionScope . You need to start a new TransactionScope if you need to undo changes made only by this method.

 using (MusicContainer music = new MusicContainer())
   {
     using (TransactionScope transaction = new TransactionScope(TransactionScopeOptions.RequiresNew))
          {
              Artist artist = new Artist { Name = "Test" };
              music.Artists.AddObject(artist);
              music.SaveChanges();
              scope.Complete(); 
          }
    }
0
source

All Articles