我是否正确使用TransactionScope和DataContext? [英] Am I using TransactionScope and DataContext properly?
问题描述
如果我新建一些DataContext,读取一些数据,然后仅将SubmitChanges包装在TransactionScope中,该怎么办?
What if I new up some DataContexts, read some data, and then only wrap the SubmitChanges in a TransactionScope?
string conn1 = GetConn1();
string conn2 = GetConn2();
using (DataContext1 dc1 = new DataContext1(conn1))
{
List<Customer> customers = ReadSomeData(dc1);
ModifySomeCustomers(customers); //performs local modification to Customer instances
using (DataContext2 dc2 = new DataContext2(conn2))
{
List<Order> orders = ReadSomeData(dc2);
ModifySomeOrders(orders); //performs local modification to Order instances
using (TransactionScope scope = new TransactionScope())
{
dc1.SubmitChanges();
dc2.SubmitChanges();
scope.Complete();
}
}
}
第一个SubmitChanges调用应从池中获取一个连接,并将该连接注册到作用域中. 启用了MS DTC-预期第二个SubmitChanges调用将事务提升为分布式",从池中获取一个连接,并将该连接列入作用域.
The first SubmitChanges call is expected to fetch a connection from the pool and enlist that connection in the scope. MS DTC is enabled - the second SubmitChanges call is expected to promote the transaction to "distributed", fetch a connection from the pool and enlist that connection in the scope.
我担心ReadSomeData可能会使连接保持打开状态,因此SubmitChanges不会从池中获取连接,因此不会在范围内注册该连接.
I'm concerned that ReadSomeData may have left the connection open, so SubmitChanges doesn't fetch a connection from the pool, and therefore doesn't enlist the connection in the scope.
推荐答案
SubmitChanges
将参加TransactionScope
.
如果SubmitChanges
找到一个环境事务,则该事务将加入该事务,否则它将在SubmitChanges
方法的生命周期内自行创建事务.
If SubmitChanges
finds an ambient transaction it enlists to that transaction, otherwise it creates a transaction itself for the lifetime of the SubmitChanges
method.
关于SubmitChanges
中的事务处理,有 MSDN文章.
There is an MSDN Article about the transaction handling in SubmitChanges
.
这篇关于我是否正确使用TransactionScope和DataContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!