我怎么能知道一个SQLException被抛出,因为外键冲突?抛出、冲突、我怎么能、SQLException

2023-09-02 23:43:30 作者:丑个无期徒刑

我想告诉大家,一个纪录没有被删除,因为它有子数据的用户,但我怎么能肯定的是,抛出异常,因为一个外键冲突?我看到有一个用于所有SQL异常抛出SQLException类。

I want to tell the user that a record was not deleted because it has child data, but how can I be sure that the exception was thrown because of a foreign key violation? I see that there a sqlexception class that is used for all sql exception.

推荐答案

您使用的是SQL Server的假设。

Assume you're using 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是你的男人。

Case 547 is your man.

更新以上是样品code和不应使用。请按照链接来解释为什么。

UPDATE The above is sample code and should not be used. Please follow the link as to explain why.

 
精彩推荐