关于级联删除
,当用户想要删除
字段和发生异常
时,我想在c#
中向用户显示消息code>,但不知道 此错误的编号
。请帮助我。
try{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
if(ex.number == (?))
MessageBox.Show("could not deleted, used in other tables");
}
最佳答案
马苏德
这个链接对如何做到这一点有一个有趣的解释。 http://blogs.msdn.com/b/tomholl/archive/2007/08/01/mapping-sql-server-errors-to-net-exceptions-the-fun-way.aspx
你会得到一些类似的东西:
try
{
db.ExecuteNonQuery();
}
catch (SqlException ex)
{
if (ex.Errors.Count == 1) // 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);
}
}
else throw;
}
我建议您向用户提供替代方案,仅显示错误消息并不是您可以提供的最佳用户体验。也许创建一个列来将条目定义为非事件状态。
关于c# - C#中级联删除异常的处理方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31088539/