4

I have the following method inside my asp.net mvc web application, and i am using Ado.net entity framework to map my current database tables:-

public void changeDeviceSwitch(int fromID , int toID)
{
     var currentdevices = tms.TMSSwitchPorts.Where(a => a.SwitchID == fromID);
     foreach (var d in currentdevices)
     {
          tms.TMSSwitchPorts.Remove(d);            
     }
     foreach (var d in currentdevices)
     {
          TMSSwitchPort tsp = new TMSSwitchPort() 
                { SwitchID = toID,
                  TechnologyID = d.TechnologyID,
                  PortNumber = d.PortNumber };
          tms.TMSSwitchPorts.Add(d);
     }
     tms.SaveChanges();    
}

My above method will generate multiple delete and add operations inside the database. so let say it will result in 5 delete operations and 5 insert operations, in this case will calling the SaveChangies() in my case, wraps the 10 operations in one database transaction ?, so either all changes happen or none of them ? Thanks

Kevin Fichter
  • 1,067
  • 1
  • 11
  • 17
John John
  • 1
  • 72
  • 238
  • 501
  • Possible duplicate of http://stackoverflow.com/questions/815586/entity-framework-using-transactions-or-savechangesfalse-and-acceptallchanges – mclaassen May 28 '14 at 01:02

1 Answers1

5

That is correct, SaveChanges acts like transaction meaning nothing is happening until you call it explicitly (nothing is sent to DB), and once you call it, everything is sent at once, and if one query/command fails, no changes will be persisted.

If you however want to send queries to SQL in batches, but still treat them as single transaction, you might look into what Entity Framework 6 has to offer (MSDN Article). Basically, you can wrap several SaveChanges in one big transaction, and if any of the queries/commands sent to SQL fails, in any of the batches, it will allow you to do a rollback of everything.

Admir Tuzović
  • 10,997
  • 7
  • 35
  • 71
  • thanks for the reply , so by default all my delete & Add operations will be send as one transaction ? , although when i monitor the sql profiler i can see that it will initiate separate add and delete operation, but i think this does not mean that they are not wrap in one transaction ,, right ? – John John May 28 '14 at 09:06
  • 1
    Yes, unfortunately due to lack of support for batch inserts/deletes by EF, there will be N DELETE commands and M INSERT commands, but all of those will be wrapped in a single transaction. – Admir Tuzović May 28 '14 at 09:38