1

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?

Craig
  • 18,074
  • 38
  • 147
  • 248

1 Answers1

2

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.

Community
  • 1
  • 1
Brendan Hill
  • 3,406
  • 4
  • 32
  • 61
  • Thanks. I was suspecting that. That's a bit of a short-sight of EF. Error handling. OK. Will do the checks myself. Thanks. – Craig Jul 03 '14 at 01:54
  • It might seem shortsighted of EF..... until you try to implement it yourself. I gave it a go a while ago as Entity Framework extensions and generalizing it as domain level validation is profoundly difficult! – Brendan Hill Jul 03 '14 at 01:56
  • Disagree about the no good solution. See this answer http://stackoverflow.com/questions/18714550/combination-of-two-field-must-be-unique-in-entity-framework-code-first-approach?lq=1 and this one http://stackoverflow.com/questions/9603131/where-to-run-a-duplicate-check-for-an-entity – Colin Jul 03 '14 at 11:05