C# Validation Annotation for Entity Framework only during create operations

Viewed 45

My first time posting. Normally the answer has already been provided, for which I am grateful. However, I am battling to solve a problem or determine the best practice for this specific scenario.

I understand that the [required] annotation in a .Net model will ensure that the model property is validated during create and update operations but what I want to achieve are two levels of [required].

Firstly. I would like to add a property of [RequiredDuringCreate] which, as the name suggests, would only return an error message if the property wasn't submitted during creation.

Secondly. I would like to add a property of [RequiredDuringUpdate] which, as the name suggests, would only return an error message if the property wasn't submitted during an update.

I am using Entity Framework to interact with the database and therefore determining whether something was being created for the first time or being updated would need to depend on a check of the relevant model table.

I have tried two approaches which aren't great. The first one is to check the inbound properties in the relevant controller. The second is to mark the properties [required] and then use ModelState.Remove() which works okay in .Net MVC but not in .Net Core web API.

Thanks for the advice / guidance.

1 Answers

There are probably two ways to do this. The first way is to try to inherit from the RequiredAttribute class and override the IsValid check:

public class RequiredOnCreateAttribute : RequiredAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        //... Code here   
    }
}

However, the ValidationContext might not have information if this is an insert vs. update. You could technically add a property to your entity that would set what this should be as an enum or something, but then you have to manually set it every time.

The other option is to figure out how the RequiredAttribute itself works and try to create a new one that would have a reference to the DbContext and register this inside EF... However, I have no idea if this is even possible.

Related