public object UpdateQuestion(int surveyId, Question question)
{
var surveyRepository = new SurveyRepository();
var survey = surveyRepository.LoadSurvey(surveyId);
if (!this.CanEditModule(survey.ModuleId))
{
this.DenyAccess();
}
Question questionToUpdate;
if (question.QuestionId > 0)
{
questionToUpdate =
survey.Sections.First().Questions.Where(q => q.QuestionId == question.QuestionId).Single();
questionToUpdate.RevisingUser = question.RevisingUser;
}
else
{
questionToUpdate = surveyRepository.CreateQuestion(question.RevisingUser);
survey.Sections.First().Questions.Add(questionToUpdate);
}
questionToUpdate.Text = question.Text;
questionToUpdate.IsRequired = question.IsRequired;
questionToUpdate.RelativeOrder = question.RelativeOrder;
questionToUpdate.ControlType = question.ControlType;
var answersToDelete = from answer in questionToUpdate.Answers
where !question.Answers.Any(a => a.AnswerId == answer.AnswerId)
select answer;
surveyRepository.DeleteAnswers(answersToDelete, true);
int answerOrder = 0;
foreach (var answer in question.Answers)
{
Answer answerToUpdate;
if (answer.AnswerId > 0)
{
var lambdaAnswer = answer;
answerToUpdate = questionToUpdate.Answers.Where(a => a.AnswerId == lambdaAnswer.AnswerId).Single();
answerToUpdate.RevisingUser = question.RevisingUser;
}
else
{
answerToUpdate = surveyRepository.CreateAnswer(question.RevisingUser);
questionToUpdate.Answers.Add(answerToUpdate);
}
answerToUpdate.Text = answer.Text;
answerToUpdate.RelativeOrder = ++answerOrder;
}
surveyRepository.SubmitChanges();
return
new
{
questionToUpdate.QuestionId,
questionToUpdate.ControlType,
questionToUpdate.RelativeOrder,
questionToUpdate.Text,
questionToUpdate.IsRequired,
Answers =
questionToUpdate.Answers.OrderBy(a => a.RelativeOrder).Select(
a => new { a.AnswerId, a.RelativeOrder, a.Text })
};
}