4

I have a property of entity subclass, I'd like to validate if it's null.

I can't annotate it with the [Required] attribute, because then the EF parser interprets it as required. I only want it to be required for this type (it's an inherited entity).

Thing is I use display resources in my project and I want the property name and the error message to be retrieved from resources.

The entity implements IValidatableObject, so I wanted to add Validator.TryValidateObject and get the customized validation error automatically, but it requires an instance of ValidationContext whose constructor I want to use, takes a Dictionary<object, object>, which I'm not sure what argument it requires. I'm sure this is the constructor I'm looking for, because I'm looking for a way to specify the instance and member name so the validator extracts the display variables automatically.

I don't mind doing this is in any other way, but I do prefer an out-the-box way where the system cares about formatting the validation errors with the display names of the properties and the error messages fetched from the resources.

Anyway, I'd like to ask, how does the Validator class get the display name internally? Is there anything of this functionality exposed?
Another question would be how does the ValidationContext set the MemberName internally? Ho can I construct such a ValidationContext myself?

4

1 回答 1

1

Looks like I didn't realize, but the ValidationContext.MemberName property 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 setting the property as NotRequired in the DbContext.OnModelCreating's fluent API.

于 2015-04-27T00:20:36.713 回答