I have some basic confusion about how transactions and msdtc work together.
I have a basic server/client winforms app. The app uses transactionscope to encapsulate sever
To expand on @Tuzo's explanation, here is an example of a command that will always escalate:
using(var scope = new TransactionScope())
{
using(var conn = new SqlConnection(connString)){
conn.Open();
//...some command, etc.
}
using(var conn = new SqlConnection(connString)){
conn.Open();
//...some command, etc.
}
scope.Complete();
}
In practice, the connection and command will be in another class, etc., but you get the idea. Even if the connection string is to the same database, it will escalate using DTC, because it's two connections. A non-escalating transaction would be:
using(var scope = new TransactionScope())
{
using(var conn = new SqlConnection(connString)){
conn.Open();
//...some command, etc.
//...some other command, etc.
}
scope.Complete();
}
This is better code anyway, because you open the connection, do what you need, and close as soon as possible. This does mean you have to think through your connection management. Depending on your app, you may implement this differently. For example:
using(var scope = new TransactionScope())
using(var conn = new SqlConnection(connString))
{
conn.Open();
var myService = new MyService(conn);
var myService2 = new MyService2(conn);
myService.DoSomething();
myService2.DoSomething();
scope.Complete();
}
There are various ways to implement this. Enterprise Library Data Access Application Block, and various ORMs may also help you handle your connections and transactions more efficiently.