当前位置: 代码迷 >> SQL >> 扩展Exception,增加判断Exception是否为SQL引用约束错误方法
  详细解决方案

扩展Exception,增加判断Exception是否为SQL引用约束错误方法

热度:27   发布时间:2016-05-05 10:38:24.0
扩展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"))                {                    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("该账号信息不存在或已被删除!");            }        }

 

  相关解决方案