Reputation: 1021
I have a trigger in DB that forbids inserting duplicated data. When I enter duplicated data, it adds nothing to the table, OptimisticConcurrencyException is thrown and I am swallowing (ignoring) this exception. When I try to enter new correct object, EF tries to run both INSERTs and it fails again on the first one.
How can I recover from this, all examples are discussing failed UPDATES, is there anything about INSERT? As I have read creating new DatabaseContext will solve the problem, but I cannot do it that way.
Upvotes: 0
Views: 675
Reputation: 10476
You can ask ObjectContext
to ignore all the changes after the ignorable exception is thrown. This way the added entity is marked Unchanged
; hence in the next SaveChanges
call, context won't consider it to manipulate DB:
(yourContextObject as IObjectContextAdapter).AcceptAllChanges();
Upvotes: 0
Reputation: 6491
Creating a new DatabaseContext is always the best choice (since Hibernate). In your case you need to remove the entity that caused the error from the context.
((IObjectContextAdapter)context).ObjectContext.Detach(entity);
Upvotes: 1