ASP.NET - Domain Models Validation
Hi, I have a question about validation in domain models. In my WebApi project, I used FluentValidation for validating request data in controllers. However, when creating instances of models (before, for example, saving them to the database), I would like to perform basic validation. I’ve created methods in my classes for each field (e.g., SetName), which perform basic validation and either assign the provided value to the property or throw an exception. However, as more classes are added, some methods start to repeat or the number of methods becomes quite large if there are many properties. Is there a better way to handle this? Maybe using a pattern? Or are these methods even necessary at all? I would appreciate your help as this is quite troubling to me. I am attaching a screenshot of an example class.
4 Replies
I've already expressed this in another thread. IMO validation should be done separately.
You can make helper functions on static class to be more DRY. Take a look at https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-10.0/caller-argument-expression
Caller argument expression - C# feature specifications
This feature specification describes attributes that can be used to enable the compiler to convert a caller argument expression into text. This is primarily used for debugging and testing scenarios.
you can try searching for that thread in the history
Unknown User•5mo ago
Message Not Public
Sign In & Join Server To View
Sure, I understand. Maybe I didn't explain how I handled it in my project accurately. Generally, incoming data to the API, such as UserRegisterRequest, is validated using FluentValidation just as you showed above. Then, if the validation is successful, I pass the UserRegisterRequest to the Service where a domain object UserProfile is created, and then it is passed to the repository where it is saved to the database.
The image I attached is indeed the entity, not the DTO. In the DTO, I have nothing but properties and a constructor (unless the constructor is also unnecessary, in which case I'll remove it). As for those methods, in my mind, they were supposed to finally check such basic conditions as whether the passed parameters are not null before creating the entity. Unless this is totally unnecessary and the request validation is sufficient, then in that case I will get rid of those methods.
Okay, thanks for the response. I'll delve deeper into the topic.