I have a method on a data context that takes an object, calls attach to match it with its database entry, refresh and submit any of the changes i make to the object. The update works fine the first time but when i try to update the same entry a second time it starts throwing an exception. Here is whats in my update method:
this.GetTable(data.GetType()).Attach(data, false);
this.Refresh(RefreshMode.KeepCurrentValues, data);
this.SubmitChanges();
Here is the stack trace from the exception:
System.Data.Linq.DuplicateKeyException: Cannot add an entity with a key that is already in use.
at System.Data.Linq.Table`1.Attach(TEntity entity, Boolean asModified)
at System.Data.Linq.Table`1.System.Data.Linq.ITable.Attach(Object entity, Boolean asModified)
Am I missing some sort of table refresh?
When you update the entity the second time, are you attaching it to the same DataContext instance? If you are, that’s why the exception is being thrown. You only need to attach an entity once during the lifetime of the DataContext.