Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async custom view-model validation. Impassible with .net core? Why?

I'm looking on this documentation example. It's looks like useful. For rxample I have the following view-model:

class CustomerViewModel
{
    public string Name {get; set;}
    public List<int> Roles {get; set;}
}

I would like to check if all Roles exist in my database. I'm trying something like:

class CustomerViewModel : IValidatableObject
{
    public string Name {get; set;}
    public List<int> Roles {get; set;}

    public async Task<IEnumerable<ValidationResult>> Validate(ValidationContext validationContext)
    {
        await Task.Delay(123); /// imagine that it's database call

        // and so on
    }

}

And surprise! It's impossible. It does not work. Because there is no async version of Validate( Is it possible to validate my model in model? Or I have to write separate validation services?

like image 262
Aleksej_Shherbak Avatar asked Oct 22 '25 12:10

Aleksej_Shherbak


1 Answers

The validation pipeline is not asynchronous, so it's not possible to be used for this purpose. However, that's not what it's for. Validation is about ensuring type and value correctness, not business rules such as being actual role values. That should be enforced in your business/data layer. For example, if you were using DDD, the aggregate would enforce this when adding roles to the collection of roles. This might also be something that is enforced in a repository or service for the type. Additionally, in a relational database, this would be enforced via a referential constraint, which would bubble up into your data layer, such as EF throwing an exception.

like image 50
Chris Pratt Avatar answered Oct 25 '25 01:10

Chris Pratt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!