public void SaveNewItem() { try { using (var db = new course_work_Entities()) { var pcTypeS = from p in db.pc_type where p.name.Equals(pcTypeField.Text) select p; pc_type pcType; if (!pcTypeS.Any()) { pcType = new pc_type() { name = pcTypeField.Text, }; db.pc_type.Add(pcType); db.SaveChanges(); } else { pcType = pcTypeS.First(); } var producerS = from p in db.producers where p.name.Equals(producerField.Text) select p; producer producer; if (!producerS.Any()) { producer = new producer() { name = producerField.Text, }; db.producers.Add(producer); db.SaveChanges(); } else { producer = producerS.First(); } var pc = new pc() { name = nameField.Text, description = descriptionField.Text, pc_type1 = pcType, producer1 = producer }; db.pcs.Add(pc); db.SaveChanges(); Init(); } list.SelectedIndex = list.Items.Count - 1; } catch (Exception) { MessageBox.Show("Щось пішло не так", "Помилка"); } }
public void SaveItem() { try { var index = list.SelectedIndex; using (var db = new course_work_Entities()) { var pcTypeS = from p in db.pc_type where p.name.Equals(pcTypeField.Text) select p; pc_type pcType; if (!pcTypeS.Any()) { pcType = new pc_type() { name = pcTypeField.Text, }; db.pc_type.Add(pcType); db.SaveChanges(); } else { pcType = pcTypeS.First(); } var producerS = from p in db.producers where p.name.Equals(producerField.Text) select p; producer producer; if (!producerS.Any()) { producer = new producer() { name = producerField.Text, }; db.producers.Add(producer); db.SaveChanges(); } else { producer = producerS.First(); } var pcs = (from p in db.pcs select p).ToArray(); var pc = pcs[index]; var deleteFlag = true; foreach (var p in pcs) { if (!p.Equals(pc) && p.pc_type1.name.Equals(pc.pc_type1.name)) { deleteFlag = false; } } if (deleteFlag) { db.pc_type.Remove(pc.pc_type1); } deleteFlag = true; foreach (var p in pcs) { if (!p.Equals(pc) && p.producer1.name.Equals(pc.producer1.name)) { deleteFlag = false; } } var components = (from c in db.components select c).ToArray(); foreach (var c in components) { if (c.producer1.name.Equals(pc.producer1.name)) { deleteFlag = false; } } if (deleteFlag) { db.producers.Remove(pc.producer1); } pc.name = nameField.Text; pc.description = descriptionField.Text; pc.pc_type1 = pcType; pc.producer1 = producer; db.SaveChanges(); Init(); } list.SelectedIndex = index; } catch (Exception) { MessageBox.Show("Щось пішло не так", "Помилка"); } }