Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4.1: Override IEnumerable<ValidationResult> Validate

    public abstract class Animal , IValidatableObject
    {
        public string Id {get;set;}
        public string Name {get;set;}
        public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (this.Name == "animal")
            {
                yield return new ValidationResult("Invalid Name From base", new[] { "Name" });
            }
        }
    }




    public class Dog: Animal, IValidatableObject
    {
        public string Owner {get;set;}

  public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        /*
          Here call base validate
         */

        if (this.Name == "dog")
        {
            yield return new ValidationResult("Invalid Name From dog", new[] { "Name" });
        }
    }     

    }

I have a base class Animal which implements IValidatableObject, now from Dog sub-class's Validate method which also implements IValidatableObject, I want to call base class's Validate method.

I tried doing (it doesn't call base class's validate)

base.Validate(validationContext);
like image 467
Rusi Nova Avatar asked Aug 14 '11 14:08

Rusi Nova


1 Answers

In your code sample you did not derive your dog class from Animal. The animal's validation method will only be called if you iterate through the result set:

public class Dog : Animal
{
  public override IEnumerable<ValidationResult> Validate(ValidationContext      validationContext)
  {
     foreach(var result in base.Validate(validationContext))
     {
     }

     //dog specific validation follows here...
  }
}

Only calling base.Validate() without iterating through the returned collection will not call the base's validation method. Hope, this helps.

like image 168
Hans Avatar answered Nov 15 '22 08:11

Hans