首页 > 解决方案 > 为 C# 父/子对象构建 SQL 插入事务

问题描述

我正在用 C# 开发一些商业软件对象。每个对象都有能力将自己保存到这样的关联数据库中(每个对象):

public void Save()
{
    //Collect object attributes and convert to SQLParameters
    //Add SQL Parameters to SQL command and BeginTrans   
    //Execute, if No Errors, commit, otherwise rollback   
}

我已经开始实现继承/父子部分,但我不知道如何使用内部子对象构造父对象 Save() 函数,因为:

例如:

做这个的最好方式是什么?

我想将保存(参数格式化、执行和回滚)的逻辑封装在每个对象中,即

像这样:

public void ParentSave()
{ 
   Begin Transaction

   Try
   {
   //For each CHILD Object
   //ChildObject.Save()
   }
   Catch(Save Fail)
   {
      //Rollback all executed saves/transaction(s)
    }

   IF(Success)
   {
      //Save parent
      Commit parent/overall transaction
    }
}

我知道我可以使用“事务”范围,但我不确定如何构建它,或者我是否应该有“嵌套”事务范围。我以前从未使用过事务范围。我知道 Transaction 适用于嵌套的 Begin/Commit 事务(真正的提交只有在 begin trans 计数变为 1 时才会发生),但它是否适用于使用其 Connection/SQLCommand 对象的嵌套事务?

标签: c#sql-serverparent-childtransactionscope

解决方案


I would overload Save and make it a function:

public bool Save()
{
    //Open SqlConnection

    //Begin Transaction

    bool success = Save(cn, Trans);

    if (success)
    {
        //Commit

        return true;
    }
    else
    {
        //Rollback

        return false;
    }
}

public bool Save(SqlConnection cn, SqlTransaction trans)
{
    //Save self using cn and trans. If fails, immediately return false.
    //Save each child using Save(cn, trans). If any one fails, immediately return false.
    //If no failures, return true.
}

When you want to save an object, call Save() (no arguments).

Save() will create a new connection and transaction and then call Save(SqlConnection cn, SqlTransaction trans) which will attempt to save the object using the connection and transaction just created. Save(SqlConnection cn, SqlTransaction trans) will then recursively call itself on all child objects until everything is saved from the top down.

If anything fails at any point, Save(SqlConnection cn, SqlTransaction trans) will return false all the way back up the call stack to the initial Save() which will initiate the rollback. If there are no failures, it will return true which will trigger the commit.


推荐阅读