Reputation: 73
I am trying to fully embrace the separation of concerns provided by the MVC methodology, but have reached something of a roadblock that I would appreciate advice on. How do you deal with / where should you place the code for fields that are not stored in the DB back-end, but can be directly derived from it?
For example, I may have a model representing a Person. Stored info may include their Date Of Birth. Obviously, I can calculate their current age from this, but wouldn't have it stored in the DB. Now, I want to treat age as a field when accessing the person object (maybe selecting everyone over a certain age) with a Lambda. BUT, if I put the code into the model, am I not breaking the separation of concerns? Even if I do put it there, should it be calculated when the field is accessed via get, or when the object is created? What about changes to the DOB? Should the age reflect the new value immediately, or only when the record is written back?
Let us assume, for the sake of discussion, that the calculation takes a significant time to process, so we want to minimize its use.
I hope the question makes sense!
Upvotes: 0
Views: 471
Reputation: 1038720
Since the Age
field will only be displayed/needed on some views it would make sense to have this property on the corresponding view model. You could have a function that will take a Person
instance and calculate its age. So your controller could look like this:
public ActionResult Index(int id)
{
Person person = GetFromDB(id);
PersonViewModel viewModel = Map(person);
return View(viewModel);
}
and inside the Map
method:
public PersonViewModel Map(Person person)
{
var result = new PersonViewModel();
result.Age = GetAge(person.Dob);
... some other fields
return result;
}
Now the Age
property will be available to the corresponding view and can be accessed multiple times without recalculation.
Upvotes: 2