尝试NHibernate的交易时,捕捉的SQLException [英] Catch SqlException when Attempting NHibernate Transaction

查看:200
本文介绍了尝试NHibernate的交易时,捕捉的SQLException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要看所产生的错误code一的SQLException - 但是,我不能得到一个火灾。我使用NHibernate和对我的表 SQL唯一约束设置。当违反约束,我需要捕获错误code和生产基于关闭的,用户友好的消息。这里是我的try / catch的示例:

I need to see an errorcode produced by a SqlException - however, I can't get one to fire. I use NHibernate and have a SQL UNIQUE CONSTRAINT setup on my table. When that constraint is violated, I need to catch the error code and produce a user-friendly message based off of that. Here is a sample of my 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 属性:

Check this out which illustrates how to catch a GenericADOException and look at the 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
    }
    ...
}

这篇关于尝试NHibernate的交易时,捕捉的SQLException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆