void btnSave_Click(object sender, RoutedEventArgs e) { try { if (String.IsNullOrEmpty(db.SelectedSerial.Name)) { throw new Exception("Serials name can't be empty"); } foreach (var series in db.SelectedSerial.Series) { if (String.IsNullOrEmpty(series.Name)) { throw new Exception("Series name can't be empty"); } } var duplicateName = db.SelectedSerial.Series.GroupBy(x => x.Name).Where(x => x.Count() != 1).Select(x => x.Key).ToList(); var duplicateNumber = db.SelectedSerial.Series.GroupBy(x => new { x.Season, x.Number }).Where(x => x.Count() != 1).Select(x => x.Key).ToList(); if (duplicateName.Count > 0 || duplicateNumber.Count > 0) { throw new Exception("Can't insert duplicate value"); } if (AddNew) { db.AddSerial(db.SelectedSerial); AddNew = false; } var deleted = db.GetSeries().Where(s => s.Id_Serial == db.SelectedSerial.Id).Except(db.SelectedSerial.Series).ToList(); foreach (var item in deleted) { db.DeleteSeries(db.GetSeries().First(s => s.Id == item.Id)); } db.SaveChanges(); MessageBox.Show("Saved", "Info", MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }