How to maintain transactions in two different databases
I have to maintain transactions between two different databases. I need to rollback if there is any error occurred in Database1 then all changes in database2 should be rollback.开发者_开发百科
I have two connection string in my web.config file.
The answer depends on if you need distributed transactions between two database server instances, or transactions between two databases in a single instance. In the first case you'll need a transaction manager like MSDTC, but in the second case the database server should be able to do the job by itself.
TransactionScope will escalate the transaction to MSDTC if necessary. The rules for this are somewhat subtle. If the two databases are on a single SQL Server 2008 instance, you shouldn't need MSDTC.
See also:
- TransactionScope automatically escalating to MSDTC on some machines?
- Common Gotchas when using TransactionScope and MS DTC
You could use the TransactionScope class:
using(var tx = new TransactionScope())
{
// TODO: your DB queries here
tx.Complete();
}
精彩评论