Search code examples
c#.nettransactionscope

Use of TransactionScope with Databases in C#


Consider the sample code fragment given below.

Do the changes done to database gets reverted when I do not write transaction.Complete(); in the end ?

   using (var transaction = new System.Transactions.TransactionScope())
    {

      var database = new DatabaseContext();

      var userA = database.Users.Find(1);

      var userB = database.Users.Find(2);
      userA.Name = "Admin";

      database.SaveChanges();
      userB.Age = 28;
      database.SaveChanges();
      transaction.Complete(); // Do changes done by database.saveChanges(); gets reverted if this statement is ommited ? 
}

Thanks in Advance.


Solution

  • Yes it does.

    But why do you need it? In the given example a simple database context does what you are asking for.

    If you don't call database.SaveChanges() the next time database will open a new connection on that specific location it will not contain the old data.

    I'm a little bit cautious about transaction scopes...