ASP.NET Web API validation attributes in DTO?

I use ASP.Net Web API and First Entity Framework, and from what I read, you should usually show DTO objects and not entity objects directly in your action methods (according to http://www.asp.net/web -api / overview / data / using-web-api-with-entity-framework / part-5 ).

So, in one case that I am working on to avoid the β€œoversubscription” problem, as described in the link above, I created a DTO object with almost all of the same properties as the model object. However, I wonder if I need to duplicate all the same sets of validation attributes (for example, [Required], [Range (N, M)], etc. For DTO and model properties? Initially, I was hoping (to avoid duplication ), but you need DTO check attributes if you want to use a binding check (for example, ModelState.IsValid) and the main model if you want your database to be created with the appropriate restrictions ([Required] β†’ not null, etc. d.)

Is there a better way?

Also, are there some attributes that Entity uses, but not model binding verification? For example, while [Range (n, m)] will explicitly affect validation on any client input, does it even take care of it at all (this does not seem to affect the created database schema from what I can to tell?)

+6
source share
1 answer

Entities should only have attributes that actually affect the database. DTOs should not have any attributes to check, except for DataMemberAttribute, to determine if a property is required and in what order it should be displayed, etc. For OData, you also need to install KeyAttribute. Models must have validation attributes. Since the DTO and the models are probably almost identical, you create for each dto that should be checked by the model, and just change the dto value to the model object. Now you can check it if you are not using ValidationAttributes for models that you can test them, for example, using FluentValidation

Shortly speaking:

  • Entities only get attributes that actually affect the database schema.

  • DTO - simple objects without validation logic, except for DataMemberAttribute

  • Models must have validation attributes (only if necessary, not required when using FluentValidation)

The workflow for POST will be: -> DTO included β†’ Swap dto to Model β†’ Confirm Model β†’ Swap Model for Entity β†’ Save the object to the database β†’ Use the updated object and change it to a new dto β†’ Return dto

Hello Voltomagnetic

+6
source

Source: https://habr.com/ru/post/979025/


All Articles