Controller -> Service -> Repository: Does service map Entity to ViewModel?

坚强是说给别人听的谎言 提交于 2019-12-03 09:51:25

问题


I haven MVC app, with "M" including Service and Repository layers.

However, I am a little confused as to where and how to do a couple of things.

  1. One Service calling two repositories, or calling it's own repository and another service

e.g.

I have a ReferenceDataService, which handles all of the logic for CRUD with my reference tables.

Then in my "CustomerService" I need to 'R' my reference data to get e.g. Description instead of Id. So, do I call the ReferenceDataService or ReferenceDataRepository?

  1. At some layer I'd like to map from Entity to ViewModel.

Do I do this in my Service layer, or in the Controller?

e.g. Does my ServiceLayer do the mapping/logic from VM to Entity and back?

Thanks:)


回答1:


  • Repositories talk to an underlying data source.
  • Service layer talks to repositories with domain models. It takes/passes domain models from/to the repository layer.
  • Controller talks to service layer. Controller takes/passes domain models from/to the service layer.
  • Controller calls mapping layer (if any) to map between the domain models and view models. If you don't have a mapping layer you could do the mapping in your controller although this could quickly become cumbersome in which case AutoMapper could serve as a very handy mapping layer.

Another more simpler scenario is when you don't need a service layer which is often the case in smaller applications. A service layer brings no benefit. So the controller talks directly to the repositories with the domain models.




回答2:


ViewModel contains data, required for displaying model on view. If you'll use another view (e.g. mobile application, or desktop application, or even web service) you will require another data to be displayed on view. If you'll do mappings on service layer, then you will not be able to use it with another type of application. Thus controller is a place where you map domain data to display them on view (whatever type of view you have).



来源:https://stackoverflow.com/questions/11538592/controller-service-repository-does-service-map-entity-to-viewmodel

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