【问题标题】:How do you retrieve the Exception number from DbUpdateException in Asp.net 5如何从 Asp.net 5 中的 DbUpdateException 中检索异常号
【发布时间】:2015-12-04 23:46:50
【问题描述】:

我宁愿不进行字符串比较,看起来我的例外编号在 InnerExeption 编号字段中,但是如果我尝试直接访问它,则会出现构建错误。

try {
    db.SaveChanges();
} catch (Microsoft.Data.Entity.DbUpdateException ex) {
    // ex.InternalException.Number won't compile but appears to be there

    // ex.InternalException.Message does compile but I think it seems less clean than a const comparison
}

一旦我得到这个数字,有没有我可以比较的常量?我正在尝试检查重复键错误。

谢谢

【问题讨论】:

  • 我没有see DbUpdateException.Number
  • 在这篇文章中查看来自 'Colin' 和 'a-h' 的答案:stackoverflow.com/questions/22490842/… -- 我认为他们捕获异常并提供反馈的方法应该提供详细信息您正在寻找。

标签: asp.net asp.net-core-mvc


【解决方案1】:

我找到了办法。

db.User.Add(user);
try {
    db.SaveChanges();
} catch (Microsoft.Data.Entity.DbUpdateException ex) {
    if (((System.Data.SqlClient.SqlException)ex.InnerException).Number == 2627) {
        return new HttpStatusCodeResult(409);
    }
}

【讨论】:

  • 谢谢,我等了 2 天然后忘记了
  • 就我而言,我必须使用 Microsoft.Data.SqlClient 而不是 System.Data.SqlClient
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-02
  • 2014-11-18
  • 1970-01-01
  • 1970-01-01
  • 2010-09-07
  • 2019-05-09
  • 1970-01-01
相关资源
最近更新 更多