开发者

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 c开发者_如何转开发ombines 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?


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.


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)
   }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜