Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Should I use the Repository Pattern to write ViewModels to the database or convert them to Models first?

In my ASP.NET MVC app, I have a fairly complex edit page which combines a number of models into one view.

I'm using the ViewModel pattern to combine all of this information and present one cohesive object to the View.

As an example, my ViewModel structure is something like this:

CompanyId
CompanyName
List<Employee> Employees
List<ContactMethod> ContactMethods

The Employee object has a number of basic properties, and a preferred contact method.

On the edit page, the user is given all of the employees of the company and they have the ability to add and remove (using javascript), as well as edit employee details. The ContactMethods list is used to populate the dropdown for each employee.

I've successfully translated my Models (read from the database) into this ViewModel and back again, so after an edit, I'm left with a ViewModel representing the current state of that company's employees.

I'm using a Repository pattern to communicate with the database, so my question is, should I call directly into the CompanyRepository, passing the ViewModel, or should I convert the ViewModel back into Model objects first before using the Repository to write them to the database?

In short, should the Repository know about my ViewModel objects?

like image 580
Damovisa Avatar asked Mar 16 '10 04:03

Damovisa


1 Answers

I would convert the ViewModel back into Model objects first. I like keeping the dependency between my Web layer and Repository layers as loose as possible.

I don't think your Repository should know about your ViewModel, since that's a web level concept.

like image 195
reustmd Avatar answered Sep 17 '22 21:09

reustmd