Databases Reference
In-Depth Information
Obviously, a yellow page of death is not acceptable in a production-ready web
application, and you need to change it to report the error consistently with other valida-
tion results implemented in the application code. In particular, you need to catch the
appropriate exceptions and rethrow them wrapped inside of
ValidationException
instances. Here is how you can override the
SaveChanges
method of the
NorthwindEntities
class to do this:
public override int SaveChanges(SaveOptions options)
{
try
{
return base.SaveChanges(options);
}
catch (UpdateException e)
{
HandleSqlException(e);
throw;
}
}
The new version of the
SaveChanges
method puts the call to the base method inside of a
try/catch
block to intercept database errors reported as instances of the
UpdateException
class by the Entity Framework. The
UpdateException
itself provides a very generic error
message saying that an error has occurred when trying to save changes; however, the
underlying database error is still available through its
InnerException
property used in the
HandleSqlException
method shown here:
private static void HandleSqlException(Exception e)
{
SqlException error = e.InnerException as SqlException;
if (error != null)
{
if (error.Number == 547)
HandleReferenceConstraintViolation(error);
else if (error.Number == 2627)
HandleUniqueKeyConstraintViolation(error);
}
}
In this example, Microsoft SQL Server is used, so the inner exception will be of type
SqlException
defined in the
System.Data.SqlClient
namespace. You can determine what
kind of error has occurred by looking at the SQL error
Number
, which for the violation of a
UNIQUE KEY
constraint will be
2627
and for a
FOREIGN KEY
violation will be
547
.