我使用EF作为ORM并删除了一条记录,我正处于异常
之下"The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Students_dbo.Classes_Class_ClassID". The conflict occurred in database "Demo.DataAccess.DemoContext", table "dbo.Students", column 'Class_ClassID'.
The statement has been terminated."
我能理解这是因为这张唱片的PK在其他表的记录中被称为FK。问题是如何妥善处理?我的代码正在处理ConstrainException
和sQLException
但是这个错误并没有被他们捕获,而是由Exception
处理,请参阅下面的代码:
public void DeleteClass(int Id)
{
try
{
unitOfWork.ClassRepository.Delete(Id);
unitOfWork.Save();
}
catch (ConstraintException e)
{
throw e;
}
catch (SqlException e)
{
throw;
}
catch (Exception e)
{
throw e;
}
}
问题: 如何具体处理?异常处理每个错误,但我需要知道什么时候这个"约束"异常火灾。基于异常类型,我需要做不同的事情。
答案 0 :(得分:1)
试试这个
catch (DbEntityValidationException e)
欢呼声