简体   繁体   中英

Rollback transaction with 2 DbContexts in Entity Framework. Use TransactionScope or TransactionBegin?

I have a 2 DbContext' s that I call both of them in one form as you can see here:

    dbcontext1.add(object);
    dbcontext1.save();
    dbcontext2.add(object);
    dbcontext2.save();

So I have a question: if some problems happen and my record saved by DbContext1 but not in DbContext2 , I need to rollback my transaction.

I searched and I found two methods: using BeginTransaction and TransactionScope . I am confused about which one I should use and what the differences between them are?

I found something like this but i don;'t know how can i roll back this :

using (TransactionScope scope = new TransactionScope())  
{
  using (EFEntities1 dc = new EFEntities1())
  {
     dc.USERS.Add(user);
     dc.SaveChanges();
  }

  using (EFEntities2 dc = new EFEntities2())
  {
     dc.USERS.Add(user);
     dc.SaveChanges();
  }

  scope.complete();
}

Best regards

I am confused about which one I should use and what the differences between them are?

The difference is that TransactionScope behaves like a regular, lightweight and local transaction as long as you use it with a single database connection (SQL Server 2005) or with multiple connections on the same database (SQL Server 2008 and up). If the two or more connections are used within the same transaction scope or more than one databases are accessed (again, depending on SQL Server version), then it is promoted to a distributed transaction (so registered with MSDTC). In your case, it will be promoted.

I found something like this but i don;'t know how can i roll back this.

As long as you don't call Complete , the transaction scope is rolled back as soon as the scope ends (eg dispose, the using ends, etc).

If an exception is thrown by either of the db contexts, then in your code Complete will not be called and the transaction is going to be rolled back.

From MSDN:

If no exception occurs within the transaction scope (that is, between the initialization of the TransactionScope object and the calling of its Dispose method), then the transaction in which the scope participates is allowed to proceed. If an exception does occur within the transaction scope, the transaction in which it participates will be rolled back.

This is also the reason why a Rollback method does not exist.

You might also want to look into what isolation level to use with it. The default is Serializable .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM