在尝试NHibernate事务时捕获SqlException
问题描述:
我需要看到由SqlException
产生的错误代码 - 但是,我无法启动一个。我使用NHibernate,并在我的桌子上安装了SQL UNIQUE CONSTRAINT
。当违反这个约束条件时,我需要捕获错误代码并基于此创建一个用户友好的消息。这里是我的try/catch的示例:在尝试NHibernate事务时捕获SqlException
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
属性看:
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
}
...
}
你达人!非常感谢。我喜欢这个网站。 – BueKoW 2011-03-22 14:58:08
@BueKoW,不要忘记将答案标记为已接受。 – 2011-03-22 15:22:38