c# - 英孚。在没有 DbContext 的情况下调用实体验证

标签 c# entity-framework unit-testing validation

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

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

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

这是我的实体的代码:

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

关于c# - 英孚。在没有 DbContext 的情况下调用实体验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14710969/

相关文章:

c# - 如何以编程方式检测操作系统 (Windows) 何时唤醒或 hibernate

c# - 比较 LINQ 和 C# 中的日期

c# - 存储用于 SQL 和 C# 的常量

java - 如何使这个 SwingWorker 代码可测试

c++ - 我需要实现模板功能的特化,该功能执行查找两个C风格字符串中较小的字符串的功能

c# - 自动夹具 + AutoMoq : Create mock with excluded property

c# - Lambda 表达式中的动态 Where 子句

mysql - mysql中的EF自引用表

c# - "The underlying provider failed on Open"

unit-testing - 为什么使用集成测试而不是单元测试是一个坏主意?