public QuestionResponseModel AddQuestion(QuestionRequestModel model) { this.SetCorrectContentType(); if (!this.IsModelValid(model)) { throw new WebFaultException(HttpStatusCode.BadRequest); } var question = new Question(); question.Text = model.Text; question.Category = this.LoadOrCreateCategory(model.Category); question.DifficultyLevel = (DifficultyLevel)Enum.Parse(typeof(DifficultyLevel), model.Difficulty); question.Answers = this.GetAnswersFrom(model); this.data.Get<Question>() .Add(question); this.data.SaveChanges(); WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Created; return QuestionResponseModel.FromQuestion .Compile().Invoke(question); }
private bool IsModelValid(QuestionRequestModel model) { if (model == null) { return false; } if (string.IsNullOrEmpty(model.Category)) { return false; } if (string.IsNullOrEmpty(model.Text)) { return false; } if (string.IsNullOrEmpty(model.Difficulty)) { return false; } if (model.CorrectAnswers == null || model.CorrectAnswers.Count() < 1) { return false; } if (model.WrongAnswers == null || model.WrongAnswers.Count() < 1) { return false; } return true; }
private ICollection<Answer> GetAnswersFrom(QuestionRequestModel model) { var answers = new List<Answer>(); model.CorrectAnswers .Select(text => new Answer(text, true)) .ForEach(answers.Add); model.WrongAnswers .Select(text => new Answer(text)) .ForEach(answers.Add); return answers; }