EF。在没有DbContext的情况下调用Entity上的验证

时间:2013-02-05 15:26:34

标签: c# entity-framework unit-testing validation

是否可以在不使用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)
   {
      ...
   }

   ...
}

1 个答案:

答案 0 :(得分: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....

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

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

}