Reputation: 5760
I m using EF as ORM and on deleting a record I m getting below exception
"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."
I can understand it is because this record's PK is being refereed as FK in other table's records. Question is how to properly handle it ? My code is handling ConstrainException
and sQLException
but this error is not being caught by them rather it is being handled by Exception
, Please see below code:
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;
}
}
Question: How to handle it specifically ? Exception handles every error but I need to know when expectly this "Constraint" exception fires. Based on exception type I will need to do different things.
Upvotes: 1
Views: 3282