Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF CodeFirst handling database exceptions while saving changes

Since EF doesn't support unique key contraints, it seems that we need to catch exception during the Save method, and display error message to user.

The problems with this approach are:

  • how do we know which record threw an exception
  • how do we know what kind of problem threw an exception (ex I could have two unique constraints on same record, so I need to tell the user which one is broken)

DBMS is SqlServer 2008.

How to resolve these problems?

like image 843
Goran Avatar asked Nov 04 '22 21:11

Goran


1 Answers

If you allow that a user can enter values that must be unique in the database you should validate this input before you save the changes:

if (context.Customers.Any(c => c.SomeUniqueProperty == userInput))
    // return to user with a message to change the input value
else
    context.SaveChanges();

This isn't only the case for values with unique constraints in the database but also for entering foreign key values that must refer to existing target records or primary key values if the primary key isn't autogenerated in the database. EF doesn't help you in the latter situation either because a context doesn't know the content of the whole database table but only about the entities that are currently attached to the context. It is true that EF will forbid to attach two objects with the same primary key but allows two objects with the same unique key constraint. But this doesn't guard you completely against primary key constraint violations when you save changes to the database.

In the unlikely case that between the Any check and SaveChanges another user has entered a record with the same value, I would consider the occuring exception as not possible to handle and just tell the user "An expected error occurred, please try again...". If the user tries again the Any check happens again and he will get the more useful message to change the input value from the code above.

The exception returned for such unique key constraint or primary key constraint violations is a general DbUpdateException and one of the inner exceptions will be a SqlException that contains as one of its properties a SQL Server error code. Any other details can be found only in the exception message "Violation of UNIQUE KEY constraint IX_SomeUniqueProperty_Index..." or similar. If you expect that the user can understand and react accordingly to this information you could display it. Otherwise you could log this message for an administrator or developer to check for possible bugs or other problems.

like image 131
Slauma Avatar answered Dec 29 '22 01:12

Slauma