【问题标题】:Trouble getting transaction working with SubSonic无法使用 SubSonic 进行事务处理
【发布时间】:2011-03-22 13:03:05
【问题描述】:

我在 ASP.NET/SQL Server 2005 中使用 SubSonic 使多删除事务工作时遇到了一点麻烦。似乎它总是在数据库中进行更改,即使没有调用 complete 方法事务范围对象?

我一直在阅读有关此的帖子并尝试了各种替代方法(切换我的 using 语句的顺序),使用 DTC,不使用 DTC 等,但到目前为止没有任何乐趣。

我会假设问题出在我的代码上,但我无法发现问题 - 有人能帮忙吗?我正在使用 SubSonic 2.2。下面的代码示例:

using (TransactionScope ts = new TransactionScope())
            {
                using (SharedDbConnectionScope sts = new SharedDbConnectionScope())
                {
                    foreach (RelatedAsset raAsset in relAssets)
                    {
                        // grab the asset id:
                        Guid assetId = new Select(RelatedAssetLink.AssetIdColumn)
                            .From<RelatedAssetLink>()
                            .Where(RelatedAssetLink.RelatedAssetIdColumn).IsEqualTo(raAsset.RelatedAssetId).ExecuteScalar<Guid>();

                        // step 1 - delete the related asset:
                        new Delete().From<RelatedAsset>().Where(RelatedAsset.RelatedAssetIdColumn).IsEqualTo(raAsset.RelatedAssetId).Execute();

                        // more deletion steps...
                    }

                    // complete the transaction:
                    ts.Complete();
                }
            }

【问题讨论】:

    标签: subsonic subsonic2.2


    【解决方案1】:

    您的 using 语句的顺序是正确的(我自己记得这个技巧的顺序:连接需要在创建事务时了解事务,它通过检查 `System.Transactions.Transaction.Current 来做到这一点)。

    一个提示:你不需要使用双括号。而且您不需要对 SharedDbConnectionScope() 的引用。 这看起来更具可读性。

    using (var ts = new TransactionScope())
    using (new SharedDbConnectionScope())
    {
        // some db stuff
    
        ts.Complete();
    }
    

    无论如何,我不明白为什么这不起作用。 如果问题与 MSDTC 有关,则会发生异常。

    我只能想象,SqlServer 2005 配置中存在问题,但我不是 SqlServer 专家。

    也许您应该尝试一些演示代码来验证交易是否有效:

    using (var conn = new SqlConnection("your connection String");
    {
        conn.Open();
        var tx = conn.BeginTransaction();
    
        using (var cmd = new SqlCommand(conn)
            cmd.ExecuteScalar("DELETE FROM table WHERE id = 1");
    
        using (var cmd2 = new SqlCommand(conn)
            cmd2.ExecuteScalar("DELETE FROM table WHERE id = 2");
    
    
        tx.Commit();
    }
    

    并且 subsonic 支持原生事务而不使用 TransactionScope:http://subsonicproject.com/docs/BatchQuery

    【讨论】:

      猜你喜欢
      • 2019-05-09
      • 1970-01-01
      • 2014-02-17
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-17
      • 2018-04-19
      相关资源
      最近更新 更多