Domain vs DTO vs ViewModel - How and When to use t

2019-01-30 20:17发布

问题:

In a Multi-layer project with Domain layer (DL)/Business (Service) Layer (BL)/Presentation Layer (PL), what is the best approach to deliver Entities to the Presentation Layer?

DO => Domain Object;
DTO = Domain Transfer Object;
VM => View Model;
V => View;

Option 1:

DL => DO => BL => DTO => PL => VM => V

This option seems to be the Best Practice but also seems heavy to mantain.

Option 2:

DL => DO => BL => DTO => PL => V

This option seems not very good practice but as DTO are almost identical to the VM, we can pass it directly to the View and it's less painfull to implement and mantain.

Is this option also reliable for multiple layouts, for example, for Mobile Devices I may need less information from the BL, so I will need a diferent VM for this particular Layout?

回答1:

It's OK to pass the DTO to the view. If you need to change or enhance the DTO then create a ViewModel. A common scenario would be to add links. It's also OK for the ViewModel to reference the DTO as a complex property.



回答2:

If you are going to have different views that require different data from your Dto it sounds like you might benefit from having different view models for these and map your Dto to these.

One of the ideas behind this is to allow greater freedom to change your view model, knowing it will not have an impact on any other part of your application. If your Dto is being used in several views then each change to your Dto would require you to test each view.



回答3:

See here my reply : https://stackoverflow.com/a/14059156/1288063

You say : This option seems to be the Best Practice but also seems heavy to mantain.

heavy to implement perhaps, juste few lines of code to duplicate most the time, but to maintain surely not.



回答4:

To me this decision is based on where I put my validation logic.

Scenario #1: Adding a data annotation in viewmodel (in UI layer) greatly simplifies programming. Mostly there will be one on one mapping between DTO and view model. In such cases Option 1 is good. DL => DO => BL => DTO => PL => VM => V

Scenario #2) If the validation is not attached to ViewModels then DTO is replaced with ViewModel and ViewModel resides in Business layer. DL => DO => BL => VM => PL => V

Scenario #2 can be perfect in situations where validation logic resides in Domain Models. And these models are used by many UI applications. UI just lists the errors in a list, as given by the business layer (not very user friendly though). As the application undergoes business rules change we only change the domain model. Again database related validations can be auto generated through EF(if using .net), even less scope for change.