本文介绍了英孚在没有DbContext的实体上调用验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不使用 DbContext 的情况下调用 Validate(..)?

Is it possbile to call Validate(..) without using DbContext?

我想在单元测试中使用它.

如果我在 Contract 对象上使用 TryValidateObject(..),则仅调用 User 属性的验证,而不会调用验证(..)

If I use TryValidateObject(..) on my Contract object - only the validation of User Property is called, but not Validate(..)

这是我实体的代码:

[Table("Contract")]

public class Contract : IValidatableObject
{
   [Required(ErrorMessage = "UserAccount is required")]
   public virtual UserAccount User
   {
      get;
      set;
   }

   public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
   {
      ...
   }

   ...
}

推荐答案

是的,您需要调用 Validator.TryValidateObject(SomeObject,...)
这是一个例子 http://odetocode.com/blogs/scott/存档/2011/06/29/manual-validation-with-data-annotations.aspx

...多汁的是....

... the juicy bit is....

        var vc = new ValidationContext(theObject, null, null);
        var vResults = new List<ValidationResult>();
        var isValid = Validator.TryValidateObject(theObject, vc, vResults, true);
        // isValid has  bool result, the actual results are in vResults....

让我更好地解释一下,在验证器调用validate例程之前,您需要使所有注释都有效,在这里我添加了一个测试程序来说明最有可能出现您的问题

Let me explain better, You need to have all Annotations Valid BEFORE the Validator will call the validate routine, here I added a test program to illustrate what is most likely your issue

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ValidationDemo
{
class Program
{
    static void Main(string[] args)
    {
        var ord = new Order();
        // If this isnt present, the validate doesnt get called since the Annotation are INVALID so why check further...
        ord.Code = "SomeValue";   // If this isnt present, the validate doesnt get called since the Annotation are INVALID so why check further...
        var vc = new ValidationContext(ord, null, null);
        var vResults = new List<ValidationResult>();    // teh results are here
        var isValid = Validator.TryValidateObject(ord, vc, vResults, true);    // the true false result
        System.Console.WriteLine(isValid.ToString());
        System.Console.ReadKey();
    }
}
public class Order : IValidatableObject
{
    public int Id { get; set; }
    [Required]
    public string Code { get; set; }
    public   IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var vResult = new List<ValidationResult>(); 
        if (Code != "FooBar") // the test conditions here
        {
            {
                var memberList = new List<string> { "Code" }; // The
                var err = new ValidationResult("Invalid Code", memberList);
                vResult.Add(err);
            }
        }
        return vResult;
    }
}

}

这篇关于英孚在没有DbContext的实体上调用验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 14:35