0

我正在返回一个RunWorkerCompletedEventArgs对象,并试图获取可以在对象中看到的错误号。当我使用if (err.Number!= 2627){}我得到以下错误

“object”不包含“Number”的定义,并且找不到接受“object”类型的第一个参数的扩展方法“Number”(您是否缺少 using 指令或程序集引用?)

请有人建议我如何获取对象内容(请参阅下面的即时窗口)。

另外请有人解释一下这里实际发生了什么,因为错误表明该对象不包含“数字”的定义,但它看起来确实存在?

代码:

private void GBHworker_RunWorkerCompleted(object sender, 
             RunWorkerCompletedEventArgs e)
{
    //update UI once worker complete his work 
    if (e.Result != null)
    {
        var err = e.Result;
        if (err.Number!= 2627) //don't want to raise error on duplicate primary key
        {
            MessageBoxButton btn = MessageBoxButton.OK;
            var result = ModernDialog.ShowMessage(e.Result.ToString(), 
                         "Error", btn);
        }
    }
}

分配 e:

private void GBHworker_DoWork(object sender, DoWorkEventArgs e)
{

  //....DB parameter setup
  try
  {
    cmd_insert.ExecuteNonQuery();
  }
  catch (Exception crap)
  {
    if (e != null)
      e.Result = crap;
  }

 }

即时窗口:

?err
{"Violation of PRIMARY KEY constraint 'PK_XYZ'. Cannot insert duplicate key in object 'dbo.XYZ. The duplicate key value is (30527293868).\r\nThe statement has been terminated."}
    base {System.Data.Common.DbException}: {"Violation of PRIMARY KEY constraint 'PK_XYZ'. Cannot insert duplicate key in object 'dbo.XYZ'. The duplicate key value is (30527293868).\r\nThe statement has been terminated."}
    Class: 14
    ClientConnectionId: {*******}
    Errors: {System.Data.SqlClient.SqlErrorCollection}
    LineNumber: 1
    Number: 2627
    Procedure: ""
    Server: "*******"
    Source: ".Net SqlClient Data Provider"
    State: 1
4

2 回答 2

2

您不需要Resultproperty 来获取异常详细信息,而是使用property 并且由于Error您期望一个SqlException,所以您可以检查ErrorSqlExceptionNumber

if (e.Error != null)
{
   var error = e.Error as SqlException;
   if(eror != null && error.Number == 2627)
     {
      //duplicate key
     }
}

目前您收到错误,因为e.Result是 type Object,您必须将其转换为特定类型才能访问其属性。

于 2013-10-09T13:13:45.813 回答
1

投射e.Result到怎么样DbException

var exp=e.Result as DbException;

if(exp!=null){
    //NOW USE IT: exp.Number;
}

Result是类型Object

编辑:- 如果您按照@Habib 的建议删除try /catch_DoWork,则使用他说明的以下代码:

var err=e.Error as SqlException;
if(err!=null && err.Number ==2627)
{
    //....
}
于 2013-10-09T13:13:06.580 回答