我如何知道是否因外键违规而抛出SQLexception?

时间:2010-03-08 17:42:32

标签: c# .net sql sql-server validation

我想告诉用户记录没有被删除,因为它有子数据,但是如何确保由于外键违规而引发了异常?我看到有一个sqlexception类用于所有sql异常。

2 个答案:

答案 0 :(得分:44)

假设您正在使用SQL Server。

使用谷歌 - http://blogs.msdn.com/tomholl/archive/2007/08/01/mapping-sql-server-errors-to-net-exceptions-the-fun-way.aspx

try
{
    # SQL Stuff
}
catch (SqlException ex)
{
    if (ex.Errors.Count > 0) // Assume the interesting stuff is in the first error
    {
        switch (ex.Errors[0].Number)
        {
            case 547: // Foreign Key violation
                throw new InvalidOperationException("Some helpful description", ex);
                break;
            case 2601: // Primary key violation
                throw new DuplicateRecordException("Some other helpful description", ex);
                break;
            default:
                throw new DataAccessException(ex);
        }
    }

}

案例547是你的男人。

更新以上是示例代码,不应使用。请点击链接解释原因。

答案 1 :(得分:-2)

你可以在Try块中编写你的异常预期代码,如果有任何异常将会被进一步捕获,现在你可以得到错误号。现在可以检查是外键违规或者不

try
 {

//your deletetion code

 }catch (SqlException ex)
    {

        if (ex.Errors.Count > 0) // Assume the interesting stuff is in the first error
        {
            switch (ex.Errors[0].Number)
            {
                case 547: // Foreign Key violation
                    lblError.Text = "Cannot Delete this Record this is associated with other record...!";

                    break;
                default:
                  throw;

            }
        }
    }