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?