ASP.NET MVC - Should I use the Repository Pattern

2019-03-19 07:36发布

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?

3条回答
戒情不戒烟
2楼-- · 2019-03-19 08:12

I would agree with the previous answer of converting ViewModels back into "plain" Models, but would add that this task should probably be carried out by a separate service layer. This layer would be responsible for disassembling your ViewModels and acting appropriately.

This is essentially the definition of a service: something whose job is to carry out a logical unit of work that requires multiple models and/or complex logic.

查看更多
家丑人穷心不美
3楼-- · 2019-03-19 08:13

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.

查看更多
该账号已被封号
4楼-- · 2019-03-19 08:14

ViewModel is the model to the view (UI), so repository shouldn't know about the view model. Separating them will keep repository loosely coupled from the UI.

Use another layer like service layer, to encapsulate repository from the UI. This layer also does the ViewModel - Model conversation and do respository call.

public class ServiceLayer
{
   public void SaveModel(ViewModel viewmodel)
   {
      var model = viewModel.ToModel();
      repository.Save(model)
   }
}
查看更多
登录 后发表回答