Reputation: 18704
I have a column in a table, that is the name of a store, for example, and it should remain unique. I have added the unique constraint to the table.
I was about to add some code to my save method, which does a check for a duplicate, before attempting the same, but ... is there any reason NOT to just do the same, make the unique constraint catch the issue, and then somehow (with entity framework), check the error, and reply with the appropriate reply?
That would save a 'SELECT'... but is it good practice to remove 'business logic' from the code, and allow the database to report such a breech?
And can I just, from the SaveChanges() command sent to Entity Framework, what the error was?
Upvotes: 1
Views: 214
Reputation: 3742
Unfortunately Entity Framework has no good solution for unique validation as I asked a while back:
Options for Unique field in Entity Framework - navigation property to dbSet?
Explicitly checking for uniqueness prior to SaveChanges() allows you to gracefully show a friendly & meaningful error message to the user.
Catching a DB error would require parsing the error code/text to find out whether it was uniqueness was violated or some other DB error occurred.
So assuming you place value on the user experience, the extra database call + minor pattern breakage is an acceptable cost IMO. The unique checking code could be generalized somehow in your domain/business layer to keep it in the right spot.
Upvotes: 2