Reputation: 10514
In a MVC app with Entity Framework 4 I am trying to add some more code to a Schedule
model. Right now a method on this model is called from code to get a list of dates that are not in the weekend. The model is called from controllers in this way var freeDates = Schedule.GetDatesNextThirtyDays()
.
To do the above, no database call is necessary. I want to add a method that checks if the date is a "structural free day" (free every year). This method needs to make a database call, since the free days will be stored in the StructuralFreeDay
model consisting of string DayMonth
(maybe I will use DateTime and ignore year part, have to watch out for leap years though - this is another problem) and string Reason
.
// get a list of dates (within the next 30 days) that are eligible for duty
public static ICollection<DateTime> GetDatesNextThirtyDays()
{
ICollection<DateTime> plannableDates = new List<DateTime>();
var date = DateTime.Today;
for (var i = 0; i < 29; i++)
{
if (!IsWeekend(date) && !IsStructuralFreeDay(date)) // <= The new method.
{
plannableDates.Add(date);
}
date = date.AddDays(1);
}
return plannableDates;
}
// return true if day is not saturday, sunday
public static bool IsWeekend(DateTime day)
{
return day.Date.DayOfWeek == DayOfWeek.Saturday || day.Date.DayOfWeek ==
DayOfWeek.Sunday;
}
I prefer to add the new method bool IsStructuralFreeDate
with the database call in the GetDatesNextThirtyDays
method, since that is where it is used. Is it okay to instantiate a DbContext
and make a call to the database in the model? Or is there a more elegant solution?
Upvotes: 2
Views: 587
Reputation: 1500
Great question user2609980 (great name also ;)). As with any meta question like this it depends as much on your environment, timeline and internal standards as it does any presumed "best practice".
For what it's worth, my instinct would be to place the function in the controller. To me models should be as close to property-bags as possible. If there's logic to be had in a model then it should be focused on transforming existing data in the model via an additional read-only parameter. I also find it cleaner to keep all UOW management to the controller where DI can be used to provide the appropriate UOW instance whether called from the site or from tests.
Hope that helps!
Upvotes: 0