【发布时间】:2012-06-21 00:46:36
【问题描述】:
我有这样的代码:
using (TransactionScope transactionScope = new TransactionScope())
{
SetDefaults(products);
// Map the SizeCollectionIds of the products
_dataAccess.MapProductSizes(products);
// Mass update and insert missing parent records to the database
_dataAccess.UpdateParents(products);
// Get ids of parent products that were newly inserted
_dataAccess.PopulateParentProductByParentSku(products);
// Insert children into database
_dataAccess.InsertProducts(products);
// Insert the UPCs into the database
_dataAccess.InsertUPCs(products);
// Get Product Ids of newly inserted records
_dataAccess.PopulateProductIds(products);
// Get just the parent products to insert the brands
List<ParentProduct> parents = (from prod in products
select prod.ParentProduct).Distinct().ToList();
// Insert ParentProductBrand record
_dataAccess.InsertParentProductBrands(parents);
// Insert the custom attribute records
_dataAccess.InsertProductCustomAttributes(products);
transactionScope.Complete();
}
我的意图是,如果在事务范围内调用的方法中的任何地方发生错误,则事务将回滚,但经过一些测试后,似乎情况并非如此,我的数据最终还是半生不熟。有什么我想念的吗?我是否必须将数据访问调用封装在它们自己的 TransactionScope 中的方法本身中才能使其正常工作?
【问题讨论】:
-
您在数据访问方法中做了哪些工作?你应该至少发布一个。如果您的数据访问方法是正确的,上述应该可以正常工作
-
如果 1)
ts.Complete()未被调用并且 2) 使用的连接已在 TS 中登记,则事务将回滚。请注意,已经打开的连接不会自动加入 TransactionScope。还要验证 DA 提供者是否 [正确] 使用 TS,并且“半生不熟”不是 DA 提供者之外的副作用的结果。 -
(那个粗体字非常重要。默认情况下,LINQ2SQL 等一些 DAL 会在每个
SubmitChanges处打开新连接。其他提供程序可能会重用相同的连接。了解更多关于此处使用的提供程序的信息——也许在 DAL 达到顶峰——会带来更有用的答案。) -
哦,所以我必须在创建 TransactionScope 后打开连接,对吗?
-
@jjm340 对于自动征募,是的 :) 您可以手动征募它(请参阅相应的 SO 问题)。
标签: c# transactions transactionscope