MikroDel
MikroDel

Reputation: 6735

EF. Call validate on Entity without DbContext

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

I want to use it in Unit Tests.

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

Here is code of my Entity:

[Table("Contract")]

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

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

   ...
}

Upvotes: 2

Views: 2244

Answers (1)

phil soady
phil soady

Reputation: 11348

Yes, you need to call Validator.TryValidateObject(SomeObject,...)
here is an Example http://odetocode.com/blogs/scott/archive/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....

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

}

Upvotes: 7

Related Questions