Programmatically check using data annotations?
I have a property of an entity subclass, I would like to check if it is null.
I cannot annotate it with an attribute [Required]
because then the EF parser will interpret it as needed. I only want this to be required for this type (it is an inherited object).
Thing is the use of display resources in my project and I want the property name and error message to come from the resources.
IValidatableObject
, Validator.TryValidateObject
, ValidationContext
, , Dictionary<object, object>
, , . , , , , .
, - , " ", , .
Anyway, I would like to ask, how Validator
does the class get the display name internally? Is there any of this feature? Another question: how does it ValidationContext
establish MemberName
internally? Can I build one myself ValidationContext
?
source to share
Looks like I didn't get it, but the property ValidationContext.MemberName
is read-write.
I ended up using the following:
public IEnumerable<ValidationResult> IValidatableObject.Validate(
ValidationContext validationContext)
{
var context = new ValidationContext(this) { MemberName = nameof(BirthDate) };
var dateResults = new List<ValidationResult>();
if (!Validator.TryValidateValue(this.BirthDate, context, dateResults,
new[]
{
new RequiredAttribute
{
ErrorMessageResourceType = typeof(ValidationResx),
ErrorMessageResourceName = Resx.Required
}
}))
foreach (var dateResult in dateResults)
yield return dateResult;
}
Another option I could do is set the property as NotRequired
in a fluent API DbContext.OnModelCreating
.
source to share