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

ryu*_*ice 21 .net c# sql sql-server validation

我想告诉用户一条记录没有被删除,因为它有子数据,但我怎么能确定由于外键违规而引发了异常?我看到有一个sqlexception类用于所有sql异常.

aro*_*ick 45

假设您正在使用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);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

案例547是你的男人.

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

  • 如果您按照链接阅读,您会注意到上面的代码是作为*不*执行的示例... (2认同)