【问题标题】:TransactionScope across Multiple Methods is not ACID?TransactionScope 跨多个方法不是 ACID?
【发布时间】: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


【解决方案1】:

看起来在您的 DataAccess 层中创建了多个数据库连接实例。尝试在 DataAccess 类构造函数中实例化您的数据库连接,并在您的 DataAccess 方法中使用它。您可能想阅读this blog post

【讨论】:

  • 不,我的数据访问层在其存在的整个过程中只打开一个连接,但根据上面的 pst 看起来我需要在创建 TransactionScope 之后创建该连接,或者连接成功'不知道要参加什么交易
  • 是的;这是最合适的方法。检查此讨论http://stackoverflow.com/questions/934316/is-there-a-way-to-use-transactionscope-with-an-existing-connection
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-24
  • 2016-08-05
  • 2010-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多