Search code examples
c#asp.net-mvcrepositoryservice-layer

How to prevent DTO`s when using asp.net MVC with domain services


I have Repositories and services. The services either orchestrate multiple repository calls or doing some in memory data logic merged with the repository calls so that I want to return DTO's. These DTOs are then perfect trimmed for the UI. But... I use asp.net mvc and my services will return DTO's to the mvc controller where I should need viewmodels. But my DTO's already nearly are like the ViewModels. The only exception is that my DTO`s do not have Validation attributes because that really belongs on the viewmodels.

What else can I do if using DTO and viewmodels together seem to much?


Solution

  • Here are some options that you can consider.
    You can trade off between options based on your requirements and scale of your application:

    • You can use an object-object mapper like AutoMappper
    • You can pass your DTOs to constructor of your ViewModels.
    • You can use a public static method of your ViewModels to create an instance of ViewModels from a DTOs.
    • In your ViewModels you can inherit from your DTOs and use a metadata class for validation attributes and then decorate your ViewModel class with [MetadadaType(typoef(YourMetadataClass))]
    • You can use your DTOs as ViewModel and the like previous option use a metadata class for validation attributes and then decorate your ViewModel class with [MetadadaType(typoef(YourMetadataClass))]

    Also I assume that your DTOs are in a separate dll than your service library.