Dakine83
Dakine83

Reputation: 707

Populating a View Model in MVC 3

I'm working on refactoring an MVC 3 web app to not pass data models directly to the controllers, but to use View models instead (See inspiration here).

Currently, when populating a list of models, we do something along these lines in the controller:

var myQuery = from t in _db.TimeEntries
select t;

List<TimeEntry> timeEntryList = myQuery.ToList<TimeEntry>();

TimeEntries is bound to our database.

Now however, I have a view model with this:

public class TimeEntryViewModel
    {

        public TimeEntry entry {get; set;}
        public Time time { get; private set; }

        public TimeEntryViewModel();
        public TimeEntryViewModel(int ID)
        {
            PraxisTime.Models.PraxisTimeDB _db = new PraxisTime.Models.PraxisTimeDB();
            entry = _db.TimeEntries.Find(ID);

            time = _db.Times.Find(entry.TimeID);
        }
    }

This is all well and good, until I want to populate a list of these. Here's my solution, added to the view model, but it feels cludgy.

public static List<TimeEntryViewModel> LoadTimeEntryViewModels(string userID)
        {
            theDB _db = new theDB();
            List<int> myQuery = (from t in _db.TimeEntries
                                 select t.ID).ToList<int>();

            List<TimeEntryViewModel> timeEntryList = new List<TimeEntryViewModel>();

            foreach (int i in myQuery)
            {
                timeEntryList.Add(new TimeEntryViewModel(i));
            }
            return timeEntryList;
        }

Is there a better way that I'm missing?

Upvotes: 1

Views: 731

Answers (1)

matto0
matto0

Reputation: 1095

Its not your view model's responsibility to know how to pull data and populate itself, its basically a dto with a little extra metadata for the view (like required etc). First go around I would have the controller make the call to your db. You can then refactor the db calls into a repository/data access layer later on as your app grows.

Also you can clean up your linq queries by doing this:

var entries = from t in _db.TimeEntries
              select new TimeEntryViewModel { entry = t.entry, time = t.time };

Also is TimeEntry you db entity? if so, you have reference to it in the view model. You are also newing up your db, I'd use some sort of dependency injection to decouple your code which will clean up your code as well as give you the ability to mock it in unit tests, and will set you up so later on you can pass in interfaces for dependancies instead of concretes.

Upvotes: 1

Related Questions