by Dominic Zukiewicz
21. August 2007 11:57
Updating multiple databases (maybe on different servers), but in a "all-or-nothing" fashion. Its something that you will come across at least once in your professional career. But how do you do it in .NET?
Transactions work great if there's just one connection to one database at a time. But what happens if you want to update several databases? Microsoft thought of that too, using something called DTC (Distributed Transaction Co-ordinator). But that's in the COM/COM+ world and we don't want to touch that do we?? No! is the answer.
Digging through the documentation (or Google :-P) you can pick up a class called
TransactionScope. TransactionScope is like a wrapper for any connections you wish to make to multiple databases. The beauty of this class is that it will even work across database implementations - e.g. Access, SQL and Oracle.
So if you were updating 3 databases, all in totally different formats and on different servers, this class will take care of it for you.
Here is a quick example of this:
using(TransactionScope tc = new TransactionScope())
{
using(SqlConnection sqlConn1 = ......)
{
using(SqlCommand comm) .......
{
}
}
using(OleDbConnection oleDbConn2 = ......)
{
using(OleDbCommand comm .......){}
}
using(OdbcConnection odbcConn3 = ......)
{
using(OdbcCommand comm.....) {}
}
tc.Complete();
}
The entries are committed when, and on when, the .Complete() method is called. If it is disposed of before this call, no changes are made to any of the databases.
Here is a link to a presentation release by Microsoft on the TransactionScope class
2074efbe-3a9c-4a13-97b5-cdea60fde691|0|.0
Tags:
Framework