0

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?

1
  • 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
    Commented Jan 11, 2012 at 12:15

1 Answer 1

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.