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); }
public HelloService(HWContext context) { //temp until db connection established context.Worlds.Add(new World { Name = "World" }); _context = context; _context.SaveChanges(); }
private void SaveChangesButton_Click(object sender, EventArgs e) { //hwController.ShowCSharpHWForm(); var hardwareInfo = new HWEntity(); hardwareInfo.Hardware_Name = HWChangesTextBox.Text; hardwareInfo.Hardware_Brand = HWBrandTextBox.Text; hardwareInfo.Hardware_Model = HWModelTextBox.Text; hardwareInfo.Hardware_Type = HWTypeTextBox.Text; hardwareInfo.Hardware_Status = HWStatusTextBox.Text; hardwareInfo.Hardware_Price = Convert.ToDecimal(HWPriceTextBox.Text); hwContext.HWEntities.Add(hardwareInfo); hwContext.SaveChanges(); RefreshView(); /* * this.Validate(); * this.hardware_PurchasedBindingSource.EndEdit(); * this.tableAdapterManager.UpdateAll(this.may2020EquipmentHWDatabaseDataSet); */ }