Should DTO and Entity both have input validations

前端 未结 3 706
轮回少年
轮回少年 2021-02-05 14:01

I have a WCF layer and my Domain Model is behind this WCF layer. I am using Nhibernate as an ORM tool and all my business logic/ Data Access etc will be behind this WCF layer.

3条回答
  •  Happy的楠姐
    2021-02-05 14:43

    having DTOs is always a good thing to hide our domain objects from any UI or external processing. This also allows you to craft a slightly different object structure because your domain model might be pretty much tight to your database diagram and must not always reflect the logical meaning of the objects.

    Meaning, no, you shouldn't expose the entities directly via services.

    To transform Entities to DTOs I'm using Automapper in most scenarios, which is pretty handy.

    Regarding validation, you can use data annotations on your entities to validate them for example.

    But if your DTOs reflect different kind of or more complex business logic which is not possible to validate with annotations alone, you could use something like fluent validation, which is very flexible and easy to setup.

    I'm currently using those in one project. For example, for standard validations like required fields, field length or even email or telephone number validation you can use simple data annotations with regular expressions etc.

    For complicated things like if field A is empty field B must not be empty etc..., you can use fluent validation... And it really depends if you do that on the entity or DTO level. If you do not have any custom logic only reflected by the DTO which could be a View Model (in terms of MVC) you can do all this on the entity level.

    It also depends if your application is the only application using the Entities. If you plan to expose your entity and data access layer as api to other developers, most of the validation should be done on that level.

提交回复
热议问题