Geoff
Geoff

Reputation: 69

Recovering from DuplicateKeyExceptions

I have a linq to SQL application I'm working on. I'm creating a new item, and was attempting to submit to database (insert). Once in a while, a duplicate key exception will happen, which is actually expected from time to time. The problem is that once the exception is thrown, I'm not able to insert valid items either. It keeps giving me the same error. Restarting the app solves the problem, and I'm able to insert the new values. Ideas?

Upvotes: 1

Views: 429

Answers (1)

Anders Abel
Anders Abel

Reputation: 69260

If SubmitChanges fails, all pending changes are kept for a retry. This makes it possible to catch the exception, update the objects and retry.

If this is a problem, you might be keeping your DataContext for too long. I assume that you are retrying, using the same DataContext. The DataContext should be a very short-lived object, that is disposed right after SubmitChanges.

An alternative is to inspect the values returned by DataContext.GetChangeSet() or the ChangeConflicts property and fix the errors and retry the submit. To remove an object from the pending insert list DeleteOnSubmit() can be used.

Upvotes: 1

Related Questions