private void saveDBBtn_Click(object sender, EventArgs e)//+ { try { using (profileContext db = new profileContext()) { using (Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction tr = db.Database.BeginTransaction()) { try { try { DataManipulationService.SaveProfileToDB(db, tr, Document); tr.Commit(); } catch (Exception ex) { tr.Rollback(); MessageBox.Show(ex.Message); return; } DataManipulationService.SaveResultToDB(db, tr, Document); } catch (Exception ex) { MainProfile mainProfile = db.MainProfile.SingleOrDefault(p => p.Name == Document.DocumentName); if (mainProfile != null) { db.MainProfile.Remove(mainProfile); db.SaveChanges(); } MessageBox.Show(ex.Message); return; } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public static void DeleteMainProfile(List <MainProfile> deletedMainProfiles) { using (profileContext db = new profileContext()) { using (var transaction = db.Database.BeginTransaction()) { try { foreach (var mainProfileItem in deletedMainProfiles) { db.MainProfile.Remove(mainProfileItem); } db.SaveChanges(); transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw new Exception("При удалении произошла ошибка. Попытайтесь снова."); } } } }
public static void SaveProfileToDB(profileContext db, Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction tr, Excel.ExcelDocument document) { Dictionary <string, QType> questionTypeMap = new Dictionary <string, QType>(); questionTypeMap = db.QType.Select(q => q).ToDictionary(q => q.Type, q => q); MainProfile mainProfile = db.MainProfile.SingleOrDefault(m => m.Name == document.DocumentName); if (mainProfile == null) { mainProfile = new MainProfile { Name = document.DocumentName }; } else { throw new Exception("Файл с таким именем уже был сохранен!"); } foreach (var profileItem in document.ProfilesListContent) { QType qType = null; if (questionTypeMap.ContainsKey(profileItem.Type)) { qType = questionTypeMap[profileItem.Type]; } else { qType = new QType { Type = profileItem.Type }; questionTypeMap.Add(qType.Type, qType); } Profile profile = mainProfile.Profile.SingleOrDefault(p => p.Name == profileItem.Name); if (profile == null) { profile = new Profile { SerialNumber = profileItem.Id, Name = profileItem.Name, Type = qType, Answer = profileItem.Answers, MainProfile = mainProfile }; mainProfile.Profile.Add(profile); } else { throw new Exception("В файле не может содержаться несколько анкет с одинаковым именем!"); } foreach (var questionItem in profileItem.Questions) { Question question = null; if (qType.Type == "range") { question = new Question { SerialNumber = questionItem.Id, Content = questionItem.Content, LeftLimit = questionItem.LeftLimit, RightLimit = questionItem.RightLimit }; } else { question = new Question { SerialNumber = questionItem.Id, Content = questionItem.Content, LeftLimit = null, RightLimit = null }; } profile.Question.Add(question); } } db.MainProfile.Add(mainProfile); db.SaveChanges(); Application.DoEvents(); }