Madhur Maurya
Madhur Maurya

Reputation: 1070

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.

Upvotes: 1

Views: 793

Answers (2)

Leandro Soares
Leandro Soares

Reputation: 2972

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...

Upvotes: 2

user844705
user844705

Reputation:

Yes.

From here...

// The Complete method commits the transaction. If an exception has been thrown,
        // Complete is not  called and the transaction is rolled back.
        scope.Complete();

https://msdn.microsoft.com/en-us/library/ee818746%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

Upvotes: 2

Related Questions