2

Validate(..)不使用就可以打电话DbContext吗?

我想在Unit Tests.

如果我TryValidateObject(..)在我的Contract对象上使用 - 只User调用属性的验证,但不调用Validate(..)

这是我的实体的代码:

[Table("Contract")]

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

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

   ...
}
4

1 回答 1

7

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

……多汁的是……

        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....

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

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;
    }
}

}

于 2013-02-05T15:48:33.733 回答