EF Handle Duplicate Values

Let’s say I have a property which should be unique.

I am wondering what’s the best way to catch unique constraint violation. I can think of two ways.

  1. Manually Check before insert if there the value already exists.
  2. Try to insert and catch exceptions

The first aproach seems inefficient and I personally think my repositories would get to bloated if they perform these checks.

The second approach seems to rely on database specific magic number exception codes. To me it also seems like unique constraint failure is something that you should expect rather than an exception (unique constraint on a `name` property for example). The try catch blocks also bloat the controller.

Which approach do you prefer? Is there another better solution to handle this problem?

submitted by /u/ll8X
[link] [comments]

Leave a Reply