I need to catch violation of UNIQUE
constraints in a special way by a C# application I am developing. Is it safe to assume that Error 2627
will always correspond to a violation of this kind, so that I can use
if (ThisSqlException.Number == 2627) { // Handle unique constraint violation. } else { // Handle the remaing errors. }
?
This issue occurs because the cached sequence is flushed incorrectly when you perform the database backup. This makes the value of the cached sequence larger than the value on the disk. In this situation, error 2627 is triggered.
To handle unique constraint violations: Catch uniqueness exceptions thrown by the database at the lowest level possible — in the UnitOfWork class. Convert them into Result.
According to your situation. Violation of UNIQUE KEY constraint: [StudentID],[Section] is composite primary key and it should be unique. [SchoolID] should also be unique. So you are trying to insert values with same ([StudentID],[Section]).
2627 is unique constraint (includes primary key), 2601 is unique index
SELECT * FROM sys.messages WHERE text like '%duplicate%' and text like '%key%' and language_id = 1033
Here is a handy extension method I wrote to find these:
public static bool IsUniqueKeyViolation(this SqlException ex) { return ex.Errors.Cast<SqlError>().Any(e => e.Class == 14 && (e.Number == 2601 || e.Number == 2627 )); }
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