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:
DBMS is SqlServer 2008.
How to resolve these problems?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With