尝试NHibernate的交易时,捕捉的SQLException

编程入门 行业动态 更新时间:2024-10-12 03:17:13
本文介绍了尝试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

本文发布于:2023-11-27 15:00:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638544.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NHibernate   SQLException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!