dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.81k stars 3.2k forks source link

How to Implement Conditionally Required Field Validation #8038

Closed spottedmahn closed 2 years ago

spottedmahn commented 7 years ago

I have field A that is required when B has a value of 'X'. How can I implement this EF Core using ASP.Net Core?

I did find this article which seems to be what I want but I'm not exactly sure how to use it in ASP.Net Core.

pmiddleton commented 7 years ago

@spottedmahn The example you are looking at is for validating the database model which is not what you are trying to do. What you want is to do is to validate the data that will be stored in the model.

Take a look at the docs for asp.net core validation here - https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/validation

What you want to do is a more advanced validation logic than the basic out of box features. For things like this I have used a library called FluentValidation. You can check it out here - https://github.com/JeremySkinner/FluentValidation

spottedmahn commented 7 years ago

@pmiddleton I was hoping I could get validation at the ASP.Net level and EF level like I get with using data annotations like [Required].

I implemented IValidatableObject and it is working in my controller via checking the ModelState

public class MyObjectViewModel : IValidatableObject{
    if(B != null
      && B.Value == "X"
      && A == null)
          yield return new ValidationResult("A is Required when the value of B is 'X'", new[] { $"{nameof(A)}"});
}
ajcvickers commented 7 years ago

@spottedmahn EF doesn't really do any "validation" even with annotations like Required. Required influences the model, and this results in some constraints with what you can do once a property is required. It also influences how we generate the database with Migrations--making the column non-nullable--such that the database will then do some validation. But there is no explicit validation done by EF Core.