0

我对编程比较陌生,正在构建我的第一个严肃的客户端应用程序。在一个表单上,我有一个按钮,它使用 SQL 数据库执行大量事务,如下所示:

private void btnALSave_Click(object sender, EventArgs e)
    {
        try
        {
            //...consider any Special Actions...//

            bool check = Automation_ALHistory_Saved(cboALHistoryType.Text);
            if (check == true)
            {
                //...create History item...//

                cHistory h = new cHistory();
                h.CaseNo = txtCaseNo.Text;
                h.HistoryType = cboALHistoryType.Text;
                h.HistoryDesc = txtALHistoryNote.Text;
                h.Save();

                //...actioned Diary marked complete...//

                cDiary.Completed(txtDiaryID.Text);                                        

                //...create new Diary (with exceptions)...//

                string strNextDiaryID = "";
                if (cboALHistoryType.Text != "Diary Cancelled" && cboALHistoryType.Text != "Case Closed")
                {
                    aMyDate cM = new aMyDate(txtALNextDueDate.Text);
                    DateTime pDate = cM.GetDate();
                    cDiary d = new cDiary();
                    d.CaseNo = txtCaseNo.Text;
                    d.DiaryType = cboALNextType.Text;
                    d.DiaryUserFor = cboALNextFor.Text;
                    d.DiaryNote = txtALNextNote.Text;
                    d.DiaryDueDate = pDate.ToString();
                    d.Save();
                    strNextDiaryID = d.DiaryID;
                }

                //...invoke KPI Manager...//

                int intActionedDiaryID = Int32.Parse(txtALDiaryID.Text);
                int intHistoryID = Int32.Parse(h.HistoryID);
                int intNextDiaryID = Int32.Parse(strNextDiaryID);
                cKPIManager kpi = new cKPIManager(intActionedDiaryID, intHistoryID, intNextDiaryID);

                //...reset forms...//

                ClearActionLinks();
                PopulateForm();
                tabCase.SelectTab("tabDiary");
            }
        }
        catch (Exception eX)
        {
            string eM = "Error attempting to save Diary / History Actions";
            aError err = new aError(eX, eM);
            MessageBox.Show(eM + Environment.NewLine + eX.Message);
        }
    }      

对于我的问题而言,所有这些都不重要。我真正需要知道的是,在运行此方法期间防止(或撤消)对数据库所做的所有更改的最佳方法是什么,如果它在任何时候都失败了。基本上我需要方法的成功(或其他)成为“全有或全无”的场景。如果该方法在最后一行失败,我需要撤消该方法之前所做的一切(就它对服务器上的数据所做的更改而言)。

对这个初学者的建议将不胜感激。

4

1 回答 1

2

使用TransactionScope

try
{
    // Encapsulate your data access code in this using
    using (TransactionScope scope = new TransactionScope())
    {


        .....

        scope.Completed();
    }
}
于 2012-06-26T09:23:12.283 回答