【问题标题】:how to handle cascade delete exception in c#如何在c#中处理级联删除异常
【发布时间】:2015-06-27 12:04:58
【问题描述】:

cascade delete 上,当用户想要delete 字段和occur exception,但不知道number of this error 时,我想在c# 中向用户显示消息。请帮帮我。

try{
    cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
    if(ex.number == (?))
        MessageBox.Show("could not deleted, used in other tables");
}

【问题讨论】:

  • 完整列表here。但进行实际检查的最佳方法是手动产生此类错误,而不是检查数字是多少。

标签: c# sql-server database exception


【解决方案1】:

马苏德,

这个链接对如何做到这一点有一个有趣的解释。 http://blogs.msdn.com/b/tomholl/archive/2007/08/01/mapping-sql-server-errors-to-net-exceptions-the-fun-way.aspx

你会有一些类似的东西:

try
{
    db.ExecuteNonQuery();
}
catch (SqlException ex)
{
    if (ex.Errors.Count == 1) // Assume the interesting stuff is in the first error
    {
        switch (ex.Errors[0].Number)
        {
            case 547: // Foreign Key violation
                throw new InvalidOperationException("Some helpful description", ex);
                break;
            case 2601: // Primary key violation
                throw new DuplicateRecordException("Some other helpful description", ex);
                break;
            default:
                throw new DataAccessException(ex);
        }
    }
    else throw;
}

我建议您向用户提供替代方案,只是显示错误消息不是您可以提供的最佳用户体验。也许创建一个列来将条目定义为非活动状态。

【讨论】:

  • 感谢您的回答
猜你喜欢
  • 2013-09-19
  • 1970-01-01
  • 2011-06-05
  • 1970-01-01
  • 1970-01-01
  • 2020-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多