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?