扩展Exception,增加判断Exception是否为SQL引用约束异常方法!

王朝学院·作者佚名  2016-05-20
窄屏简体版  字體: |||超大  

扩展Exception,增加判断Exception是否为SQL引用约束异常方法!在设计数据表时,如果将某些列设置为关联其它表的外键,那么如果对其进行增加、修改操作时,其关联表若没有相匹配的记录则报错,或者在对其关联表进行删除时,也会报错,这就是外键约束的作用,当然除了外键还有许多约束,在此暂不讨论,本篇文章主要讲的是,如何判断是否为SQL的引用约束异常,从而能够更好的将SQL复杂的报错转换为用户能够明白的友好提示。

扩展Exception,增加判断Exception是否为SQL引用约束异常方法(IsSqlReferenceConstraintException):

public static bool IsSqlReferenceConstraintException(this Exception except) { var baseEx = except.GetBaseException(); if (baseEx is SqlException) { string message = (baseEx as SqlException).Message; if (message.ToLower().Contains("reference constraint") || message.ToLower().Contains("foreign key")) { return true; } else { return false; } } else if (baseEx != null && !object.ReferenceEquals(except, baseEx))//如果基类不为空且不等于异常本身,则继续回调查找 { return IsSqlReferenceConstraintException(baseEx); } return false; }

原生的SQL报错信息如下:

The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Category_dbo.User_LastEditorID". The conflict occurred in database "mTEM", table "dbo.Category", column 'LastEditorID'.The statement has been terminated.

而采用扩展方法则会显示出我们预定义的错误信息,调用如下:

public void Remove(int userID) { User user=this.repository.Get(t=>t.ID==userID); if (user != null) { try { this.repository.Remove(user, true); } catch (Exception ex) { if (ex.IsSqlReferenceConstraintException()) //判断为引用约束错误,则直接抛出我们自定义的错误 { throw new Exception("该账号已有与之相关联的其它业务记录,禁止删除!若确认该账号停止使用,可将其设置为禁用即可。"); } } } else { throw new Exception("该账号信息不存在或已被删除!"); } }

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航