//put public string UpdateTest(InputTestDTO test) { Test testToUpdate = _testsContext.Tests.Find(test.Id); // берем тест, который нужно обновить testToUpdate.Name = test.Name; // задаем поля информации о тесте testToUpdate.DueDateTime = test.DueDateTime; testToUpdate.EstimatedTime = test.EstimatedTime; testToUpdate.QuestionsAmount = test.QuestionsAmount; testToUpdate.MaxMark = test.MaxMark; testToUpdate.IsOpen = test.IsOpen; IQueryable <Question> QuestionsConnectedWithTest = from q in _testsContext.Questions where q.TestId == test.Id select q; // удаляем все старые вопросы, связанные с тестом _testsContext.Questions.RemoveRange(QuestionsConnectedWithTest); List <int> alreadyUsedQuestionIds = new List <int>(); alreadyUsedQuestionIds = (from q in _testsContext.Questions select q.Id).ToList(); List <int> alreadyUseвAnswerIds = new List <int>(); alreadyUseвAnswerIds = (from a in _testsContext.Answers select a.Id).ToList(); // чтобы дальше их обновленную версию добавить из новой модельки теста foreach (var question in test.Questions) { question.TestId = test.Id; question.Id = Enumerable.Range(1, Int32.MaxValue).First(digit => !alreadyUsedQuestionIds.Contains(digit)); Question questionToSave = new Question() { Id = question.Id, TestId = question.TestId, Description = question.Description, QuestionTypeId = question.QuestionTypeId, Points = question.Points }; _testsContext.Questions.Add(questionToSave); alreadyUsedQuestionIds.Add(question.Id); _testsContext.SaveChanges(); foreach (var answer in question.Answers) { answer.QuestionId = question.Id; answer.Id = Enumerable.Range(1, Int32.MaxValue).First(digit => !alreadyUseвAnswerIds.Contains(digit)); alreadyUseвAnswerIds.Add(answer.Id); _testsContext.Add(answer); _testsContext.SaveChanges(); } } _testsContext.SaveChanges(); return(testToUpdate.Name); }
public ActionResult Put([FromBody] InputTestDTO test) { try { return(Ok($"Test {_testsRepository.UpdateTest(test)} was updated")); } catch (Exception e) { return(BadRequest(e.Message)); } }
public ActionResult Post(InputTestDTO test) { try { return(Ok(_testsRepository.PostCreateTest(test))); } catch (Exception e) { return(BadRequest(e)); } }
//create public string PostCreateTest(InputTestDTO test) { if (test == null) { throw new Exception("Empty test."); } // проверка, не создан ли тест с таким же именем, если создан - не добавлять if ((from t in _testsContext.Tests select t.Name).Contains(test.Name)) { throw new Exception("Test with the same name already exists."); } using (var transaction = _testsContext.Database.BeginTransaction()) { try { IEnumerable <int> alreadyUsedTestIds = from t in _testsContext.Tests select t.Id; // задаем поля информации о тесте Test testToCreate = new Test() { // присвоение добавляемому тесту id в диапазрне от 1 до int32.MaxValue, исключая те id, которые уже имеются в БД Id = Enumerable.Range(1, Int32.MaxValue).First(digit => !alreadyUsedTestIds.Contains(digit)), Name = test.Name, DueDateTime = test.DueDateTime, EstimatedTime = test.EstimatedTime, QuestionsAmount = test.QuestionsAmount, MaxMark = test.MaxMark, IsOpen = test.IsOpen, CreationDate = DateTime.Now, SubjectId = test.SubjectId }; _testsContext.Tests.Add(testToCreate); _testsContext.SaveChanges(); //если вопросы не были переданы, не добавлять их в бд. if (test.Questions != null) { List <int> alreadyUsedQuestionIds = new List <int>(); alreadyUsedQuestionIds = (from q in _testsContext.Questions select q.Id).ToList(); List <int> alreadyUseвAnswerIds = new List <int>(); alreadyUseвAnswerIds = (from a in _testsContext.Answers select a.Id).ToList(); foreach (var question in test.Questions) { question.TestId = testToCreate.Id; question.Id = Enumerable.Range(1, Int32.MaxValue).First(digit => !alreadyUsedQuestionIds.Contains(digit)); alreadyUsedQuestionIds.Add(question.Id); _testsContext.Questions.Add(question); _testsContext.SaveChanges(); if (question.Answers != null) { foreach (var answer in question.Answers) { answer.QuestionId = question.Id; answer.Id = Enumerable.Range(1, Int32.MaxValue).First(digit => !alreadyUseвAnswerIds.Contains(digit)); alreadyUseвAnswerIds.Add(answer.Id); _testsContext.Add(answer); _testsContext.SaveChanges(); } } } } transaction.Commit(); } catch (Exception e) { transaction.Rollback(); throw e; } } return("Test successfully created."); }