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

不羁岁月 提交于 2019-12-03 07:28:46

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!