13

我正在从 Gridview 发送的事件中进行级联删除。删除在事务中。这是简化的代码:

protected void btnDeleteUser_Click(object sender, EventArgs e)
{
    DataContext db;
    db = new DataContext();

    using (TransactionScope ts = new TransactionScope())
    {
        try
        {
            //delete some data
            db.SubmitChanges();

            ts.Complete();
        }
        catch (Exception ex)
        {
            // handle error
        }
        finally
        {
            db.Dispose();
            BindGridView();
        }
    }
}


private void BindGridView()
{
    DataContext db;

    db = new DataContext();

    GridView.DataSource = <my query>

    GridView.DataBind();     <========Exception

    db.Dispose();
}

调用网格的 DataBind() 方法失败,出现以下异常:“当前 TransactionScope 已完成”。为什么?

当然,此时 TransactionScope 已完成,而且应该如此。当我删除 TransactionScope 时,它​​可以工作。

4

1 回答 1

17

将 BindGridView() 移到事务范围之外。

    using (TransactionScope ts = new TransactionScope())
    {
        try
        {
            //delete some data
            db.SubmitChanges();

            ts.Complete();
        }
        catch (Exception ex)
        {
            // handle error
        }
        finally
        {
            db.Dispose();
        }
    }
    BindGridView();
于 2009-09-17T03:57:28.177 回答