I have a table with many values a few of them need to be unique. When I try to insert a row through Entity Framework and if there is a unique key violation, I am catching the exception but am trying to figure out which column caused the exception. Looking at the error message there doesn't seem to be a way to get the name of the column. If I could figure out the name of the column I could give the user a better error message.
Asked
Active
Viewed 405 times
0
-
If you surround the statement with `try {} catch {}`, and put a breakpoint on the line with `catch {}`, I think you can pinpoint the point where it gives you the exception. – Keyur PATEL Aug 26 '16 at 03:32
-
Hi Keyur, Thanks for responding. I did try that. I get an exception which says "The duplicate key value is (3)" and the next time it said "The duplicate key value is (4)". Not sure what that means. – Abbasi Aug 26 '16 at 15:32
-
From what it seems, maybe all the records you're inserting are giving that exception? Make sure you don't set the primary key from your code if it is auto-incremented in the database. Also, could you provide a part of your code so we can understand whats wrong? – Keyur PATEL Aug 29 '16 at 01:22
-
actually, this wasn't so bad. The DbUpdateException gives you the name of the unique key contraint that caused the issue. If you named you unique keys with the name of the column you get that detail from the exception. – Abbasi Aug 29 '16 at 18:58
-
Trying to add code. – Abbasi Aug 29 '16 at 18:59
-
Debug questions require a [mre]. Please clarify via edits, not comments. [ask] [Help] – philipxy Sep 19 '22 at 07:42
1 Answers
0
Ensure you have a try..catch block around your SaveChangesAsync() call, and you can use the details in the class DbUpdateException
inside the catch block. For detailed example of reading from the "inner exceptions" see this SO answer.

Anand Sowmithiran
- 2,591
- 2
- 10
- 22