public static bool InsertUpdateEntity <T>(T entity) where T : class { bool result = false; using (var context = new HWContext()) { var saved = false; while (!saved) { try { var entType = entity.GetType(); int id = (int)entType.GetProperty("ID").GetValue(entity); if (id == 0) { context.Set <T>().Add(entity); } else { context.Entry <T>(entity).State = System.Data.Entity.EntityState.Modified; } context.SaveChanges(); saved = true; } catch (DbUpdateConcurrencyException ex) { foreach (var entry in ex.Entries) { if (entry.Entity is T) { var proposedValues = entry.CurrentValues; var databaseValues = entry.GetDatabaseValues(); foreach (var property in proposedValues.PropertyNames) { var proposedValue = proposedValues[property]; var databaseValue = databaseValues[property]; // TODO: decide which value should be written to database proposedValues[property] = databaseValue; } // Refresh original values to bypass next concurrency check entry.OriginalValues.SetValues(databaseValues); } else { throw new NotSupportedException( "Неможливо опрацювати конфлікт даних " + entry); } } } } } return(result); }