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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I found a more terse solution using TryValidateObject instead of TryValidateProperty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.