Closed spottedmahn closed 2 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
@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)}"});
}
@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.
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.