简体   繁体   English

在实体框架中验证 POCO object

[英]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方法了解实体框架验证器使用的数据注释属性?

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.它基本上只是手动强制调用数据注释检查,但我找不到更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM