我需要查看由 SqlException
生成的错误代码- 但是,我不能让一个人开火。我使用 NHibernate 并且有一个 SQL UNIQUE CONSTRAINT
设置在我的 table 上。当违反该约束时,我需要捕获错误代码并据此生成用户友好的消息。这是我的 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);
}
}
请原谅我的无知。
最佳答案
Check this out这说明了如何捕获 GenericADOException
看看InnerException
属性(property):
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
}
...
}
关于c# - 尝试 NHibernate 事务时捕获 SqlException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5393044/