尝试NHibernate事务时捕获SqlException

Bue*_*KoW 1 c# asp.net nhibernate asp.net-mvc exception

我需要看到一个错误代码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);
    }
}
Run Code Online (Sandbox Code Playgroud)

请原谅我的无知.

Dar*_*rov 8

看看这个,说明了如何捕捉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
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)