尝试NHibernate事务时捕获SqlException

我需要看到一个由SqlException产生的错误代码 – 但是,我无法触发它。 我使用NHibernate并在我的表上设置了SQL UNIQUE CONSTRAINT 。 当违反该约束时,我需要捕获错误代码并根据该消息生成用户友好的消息。 这是我的try / catch示例:

 using (var txn = NHibernateSession.Current.BeginTransaction()) { try { Session["Report"] = report; _reportRepository.SaveOrUpdate(report); txn.Commit(); Fetch(null, report.ReportId, string.Empty); } catch (SqlException sqlE) { var test = sqlE.ErrorCode; ModelState.AddModelError("name", Constants.ErrorMessages.InvalidReportName); return Fetch(report, report.ReportId, true.ToString()); } catch (InvalidStateException ex) { txn.Rollback(); ModelState.AddModelErrorsFrom(ex, "report."); } catch (Exception e) { txn.Rollback(); ModelState.AddModelError(String.Empty, Constants.ErrorMessages.GeneralSaving); } } 

请原谅我的无知。

看看这个,它说明了如何捕获GenericADOException并查看InnerException属性:

 catch (GenericADOException ex) { txn.Rollback(); var sql = ex.InnerException as SqlException; if (sql != null && sql.Number == 2601) { // Here's where to handle the unique constraint violation } ... } 

我没有直接在你的控制器中捕获SqlException,而是设置了一个SQLExceptionConverter来将它转换为更有意义的exception。