ryu*_*ice 21 .net c# sql sql-server validation
我想告诉用户一条记录没有被删除,因为它有子数据,但我怎么能确定由于外键违规而引发了异常?我看到有一个sqlexception类用于所有sql异常.
aro*_*ick 45
假设您正在使用SQL Server.
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是你的男人.
更新以上是示例代码,不应使用.请点击链接解释原因.