adapter.Update 在进入 catch 块之前首先进入 Rowupdated 事件

adapter.Update first goes to the Rowupdated event before going into the catch block

我有 SqlDataAdapter

的代码
adapter.RowUpdated += adapter_RowUpdated;
try
{
    try
    {
      adapter.Update(Table);
      trans.Commit();
    }
    catch (Exception ex)
    {
       trans.Rollback();
       throw new Exception(ex.Message);
    }
}
finally
{
    adapter.RowUpdated -= adapter_RowUpdated;
}

这是我的 Rowupdated 事件

void adapter_RowUpdated(object sender, SqlRowUpdatedEventArgs e)
{
    if (e.StatementType == StatementType.Insert)
    {
       object ai = e.Command.Parameters["@SCOPE_ID"].Value;
       e.Row[_IdentityFieldName] = ai;
    }
}

这已经运行了一年多了。
但有时我在插入时遇到异常 "column xxxID cannot be null",所以我调试它,问题是当 adapter.Update(table) 失败时(例如因为违反了检查约束)下一行代码不是 Catch代码,但它首先进入 RowUpdated 事件。
在这种情况下,当然会出现一个新的异常,即 _IdentityFieldName 不能为空(它包含 table 的主字段的名称,这是一个身份字段)

然后才进入catch,但那时原来的异常从check constraint violated替换为column cannot be null

当我run/debug发生以下情况

应用程序在 adapter.Update(table) 中断,异常

The INSERT statement conflicted with the CHECK constraint "CK_PrijsAankoop". The conflict occurred in database "GTT_Test", table "dbo.tblOpdrachtCar

现在我希望它进入 catch,但它首先进入 adapter_RowUpdated 事件,然后在 e.Row[IdentityFieldName] = ai;

行抛出另一个异常

OpdrachtCarID' does not allow nulls

现在它终于进入了 catch 块,但异常现在不再是原来的异常了!

所以我的问题是,我怎样才能强制 dotnet 进行正确的异常处理并直接进入捕获状态而不先去这个事件?

这是设计使然。 RowUpdated 将在尝试更新行后引发,无论成功与否。事实上,RowUpdated 对于响应更新过程中出现的错误和异常特别有用。

事件的事件参数,SqlRowUpdatedEventArgs, has an Errors 属性 可用于获取行更新期间发生的错误。

您可以使用事件参数的 Status 属性 检查执行状态:

if (e.Status == UpdateStatus.ErrorsOccurred)  
{  
    //An error occurred
}  

要了解有关 DataAdapter 事件的更多信息,请查看 Handling DataAdapter Events