private void Save() { Messages.Clear(); contactDBContext dc = new contactDBContext(); try { //============================================ //http://patrickdesjardins.com/blog/entity-framework-ef-modifying-an-instance-that-is-already-in-the-context // you have to detach the local version and set to modify the entity you are modifying //we first verify if the entity is present inside the DbSet. If it is NOT null, than we detach the local entity. //This scenario is pretty common if you receive the object from a web request and you want to save the entity. var local = dc.Set <T003TelephoneContact>() .Local .FirstOrDefault(s => s.T003Pk == ContactRecord.T003Pk); if (local != null) { dc.Entry(local).State = EntityState.Detached; } //============================================= // Either Update or Insert child if (PageMode == PageConstants.EDIT) { dc.Entry(ContactRecord).State = EntityState.Modified; //by setting the state, then the 'SaveChanges' is able to save it's changes dc.SaveChanges(); LogTheAction(eNums.eReadUpdateCreateDelete.Update); } else if (PageMode == PageConstants.ADD) { dc.T003TelephoneContact.Add(ContactRecord); dc.SaveChanges(); LogTheAction(eNums.eReadUpdateCreateDelete.Create); } // Get all the data again in case anything changed Get(); } catch (DbEntityValidationException ex) { IsValid = false; // Validation errors foreach (var errors in ex.EntityValidationErrors) { foreach (var item in errors.ValidationErrors) { Messages.AddModelError(item.PropertyName, item.ErrorMessage); } } } // Set page state SetUIState(PageMode); }