简体   繁体   中英

What is the best place/way for server-side validation of domain model entities in .NET CORE Web API?

I have Domain model for a variety of objects. When I insert/update/delete entities through WebApi Call, I want a pre-validation of entities before that. Like For insert, if the email property of employee object already exists then throw error, similarly, for Employee object,I have other multiple Database validation to perform before I can actually perform Insert. Same goes for Update and Delete operation which has some common and some different validation to perform.Eg: For update of email email address,I will do a database call to check if employee really exists.If not then throw error.So how do I know if my operation if Insert/Update/Delete operation and then call appropriate validation methods?

I cannot make Db Call from Domain model since I don't have reference to Data Access Layer from this project.I understand that for normal field validation like range/invalid type,I can use IValidatable in my domain model.But how do I do multiple database calls.I have a service layer which currently make Db Calls for few validations for general purpose for all domain models.But how do I separate out Db Calls for each domain models?

If only a single service modifies your domain model (like a MyDomainModelService ), you can perform all validation checks there.

If this is not the case, you can create a service which checks the validity of your domain model, and use it in the places where you need it:

IValidationService<MyDomainModel> _validationService;
// ...
if (!_validationService.IsValid(model)) { throw new Exception("invalid model"); }

While it is possible to perform validation on a database level in IValidatable, it is not recommended as you need to request access to your database context by "hidden" means. Apart from that, the validation method is not async.

Another possibility is using validation attributes, in particular the [Remote] attribute. However, this approach violates some principles if you are following a clean architecture sort of style. I still wanted to mention it because in a simple application it is certainly worth considering.

Apart from that, you should reflect on whether your conditions should be part of the validation. You can make an email unique by database means or - depending on the ORM you are using - it fails (automatically) if an update is carried out on an entity / a record which does not exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM