Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

If I am creating a viewmodel to pass to a view and my viewmodel is comprised of several properties from the same object, how should I create the LINQ query? At the moment I'm doing it like this:

TaskEditViewModel viewModel = new TaskEditViewModel
 {
      Task = taskRepository.Tasks.FirstOrDefault(t => t.Id == id),
      Status = (taskRepository.Tasks.FirstOrDefault(t => t.Id == id).CompletionDate.ToString() == "") ? "close" : "open",
      Account = taskRepository.Tasks.FirstOrDefault(t => t.Id == id).Accounts.First()
 };
 return View(viewModel);

My taskRepository returns IQueryable, so does this mean I am making 3 seperate db calls? Should I be making one call and then building the viewmodel from the results?

share|improve this question
1  
I'm not knowledgeable enough to tell you what is right and whether these are multiple calls (guess it also depends on how your repository is constructed). But I would think that CompletionDate and Accounts are included in your Task model (isn't it always in LinqToSql?) so you could expose them as properties in the viewModel instead of setting them explicitly. –  Ingó Vals Jan 11 '12 at 12:15

1 Answer 1

I decided to revisit this on its anniversary. I think this would have been making multiple db calls due to lazy loading, so not very efficient.

As Ingo Vals correctly commented, the CompletionDate and Account properties are included in my Task model, so I should have just done something like this:

Task viewModel = taskRepository.Tasks.FirstOrDefault(t => t.Id == id)

return View(viewModel);

Then in my view I can get the CompletionDate and Account properties from the view model

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.