您的位置:首页 > 数据库

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

2015-04-10 11:16 381 查看
在设计数据表时,如果将某些列设置为关联其它表的外键,那么如果对其进行增加、修改操作时,其关联表若没有相匹配的记录则报错,或者在对其关联表进行删除时,也会报错,这就是外键约束的作用,当然除了外键还有许多约束,在此暂不讨论,本篇文章主要讲的是,如何判断是否为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("该账号信息不存在或已被删除!");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐