I have the following query:
var userQuizzes = from quiz in Context.Quizzes
select new DashboardQuiz
{
QuizId = quiz.Id,
Questions = quiz.Questions
QuestionExcerpt = quiz.QuizVersion.Questions.FirstOrDefault().QuestionText
// etc...
}
That's all well and good, but is it possible to call my own methods that perform logic on the data as the models are instantiated?
I have a method on my Quiz POCO class IsQuizActive() that determines from the values in Quiz if the quiz is active.
So for example:
var userQuizzes = from quiz in Context.Quizzes
select new DashboardQuiz
{
QuizId = quiz.Id,
Questions = quiz.Questions
QuestionExcerpt = quiz.QuizVersion.Questions.FirstOrDefault().QuestionText
// Custom method IsQuizActive() called here
ActiveQuiz = quiz.IsQuizActive()
}
I get an error saying that it can't be converted to LINQ, which is understandable, but I created DashboardQuiz to use as my View Model.
As it currently stands, I have to loop through my objects and create another model DashboardQuizViewModel that can be used as a view model for each item:
var userQuizzes = from quiz in Context.Quizzes
select new DashboardQuiz
{
QuizId = quiz.Id,
Questions = quiz.Questions
QuestionExcerpt = quiz.QuizVersion.Questions.FirstOrDefault().QuestionText
// I'd like to call IsQuizActive() here
}
List<DashboardQuizViewModel> responseModel = new List<DashboardQuizViewModel();
foreach (var dashboardQuiz in userQuizzes)
{
DashboardQuizViewModel viewModel = new DashboardQuizViewModel();
viewModel.QuizId = dashboardQuiz .id;
viewModel.Questions = dashboardQuiz.Questions;
viewModel.QuestionExcerpt = dashboardQuiz.QuestionExcerpt;
// Call it here instead
viewModel.ActiveQuiz = dashboardQuiz.IsQuizActive();
responseModel.Add(viewModel);
}
return responseModel;
The only other 'tidy' way that I can think of, is to have IsQuizActive as a getter on my View Model and call that from within the view. But I really want the values to be evaluated before passing it to my view model