[英]Validating a POCO object in Entity Framework
I am making an application with Entity Framework.我正在使用 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:但是,它们还使用了“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'."
}
The IsValid method I wrote doesn't know about the MaxLength attribute:我编写的 IsValid 方法不知道 MaxLength 属性:
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?如何让我的
IsValid
方法了解实体框架验证器使用的数据注释属性?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.