我正在使用实体框架制作应用程序。我有以下代码:
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();
}
}
实体框架类在进行自己的验证时会使用此验证器:
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."
}
但是,它们也使用了 'MaxLength' 属性:
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'."
}
我写的 IsValid 方法不知道 MaxLength 属性:
using (var dt = new DatabaseContext()) {
Entity en = new Entity();
en.Name = "John";
en.IsValid; // false
en.Name = "01234567890";
en.IsValid = // true;
}
如何让我的IsValid
方法了解实体框架验证器使用的数据注释属性?