0

I am making an application with Entity Framework. I have the following code:

public class Entity : IValidatableObject
{
    public int EntityId { get; set; }

    [MaxLength(10)]
    public string Name { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext = null)
    {
        if (Name == "John")
            yield return new ValidationResult("Not allowed.", new[] { "Name" });
    }

    public bool IsValid(ValidationContext validationContext = null)
    {
        return !Validate(validationContext).GetEnumerator().MoveNext();
    }
}

The entity framework classes make use of this validator when doing their own validation:

using (var dt = new DatabaseContext()) {
    Entity en = new Entity();
    en.Name = "John";
    dt.Entities.Add(en);
    String err = dt.GetValidationErrors().First().ValidationErrors.First().ErrorMessage;
    // err == "Not Allowed."
}

However, they also make use of the 'MaxLength' attribute:

using (var dt = new DatabaseContext()) {
    Entity en = new Entity();
    en.Name = "01234567890";
    dt.Entities.Add(en);
    String err = dt.GetValidationErrors().First().ValidationErrors.First().ErrorMessage;
    // err == "The field Name must be a string or array type with a maximum length of '10'."
}

The IsValid method I wrote doesn't know about the MaxLength attribute:

using (var dt = new DatabaseContext()) {
    Entity en = new Entity();
    en.Name = "John";
    en.IsValid; // false
    en.Name = "01234567890";
    en.IsValid = // true;
}

How do I get my IsValid method to know about the data annotation attributes that the entity framework validator makes use of?

Oliver
  • 11,297
  • 18
  • 71
  • 121

1 Answers1

1

You could try implementing the example shown in the accepted answer here. Its basically just manually forcing the call to the data annotation check, but I can't find a better way.

Community
  • 1
  • 1
Miika L.
  • 3,333
  • 1
  • 24
  • 35
  • Thanks. I found a more terse solution using `TryValidateObject` instead of `TryValidateProperty`. – Oliver Apr 11 '12 at 12:10