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

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

假设您正在使用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是你的男人。

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

您可以在Try块中编写exception预期的代码,如果抛出任何exception,它将进一步捕获,现在您可以获得错误编号。现在可以检查它是否是外键违规

 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; } } }