Where to load data to populate the viewmodel with more than one poco class

I need to show an object (POCO class) in the form.

In my controller, I get object data from the object repository.

But in the form I should also show some additional data about the object, such as the name of the country, not the countryid, the number of persons assigned (to get from the 1: N relationship), the history of changes (to be extracted from another table) and the "CanBeCancelled" bit .

Question: where should I put this logic?

I came up with these alternatives:

  • Repository itself: create an extra function that returns this exact view model
  • conversion service that converts the class to viewmodel (he knows where to get the data)
  • controller: it knows what data should be displayed in the view (model), so it should get all the data from different repositories

What is a good way to host this logic (using “this logic” I mean logic to know that the number of people is selected in repository A, the history is fetched by repository B, and the countryname is fetched by CountryRepository and the boolean “CanBeCancelled” is fetched by StateEngine)?

+4
source share
1 answer

If there are no other restrictions, I would follow a simple rule, formulated the principle of shared responsibility - each layer should do its own work and believe that the other layers are doing their job properly. In this case, the repositories return the business object, the services process the business object, and the controller knows how to display the object correctly. More details:

  • The number of people, the history and the name of the country are already in the repository and should come from there. Thus, the repository must return the full object - if the operations relate to the same object.

  • When several objects are involved in the process, the service is responsible for invoking the corresponding repositories and creating the object.

  • Things that are calculated according to business rules are also a job for a service object.

  • The controller receives the complete object by calling one service method and displaying it

The advantages of this approach will be obvious after you decide to change something, say, a business rule about how an object can be canceled. This has nothing to do with access to the database and does not include the application interface, so the only place you want to change in this case is the implementation of the service. This approach allows you to do just that, without having to change the code of the repositories and controllers.

+5
source

All Articles