5
    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);
Rusi Nova
  • 2,617
  • 6
  • 32
  • 48

2 Answers2

9

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.

Hans
  • 12,902
  • 2
  • 57
  • 60
  • Actually my code contains this part "public class Dog : Animal" (inherit from Animal). It was just a typo while asking the question, corrected it. – Rusi Nova Aug 14 '11 at 15:27
  • Did you try calling base.Validate() and iterating through the returned result set? This should solve your problem. The animal's Validate method gets called! – Hans Aug 14 '11 at 16:01
0
public class Dog : Animal
{
  public override IEnumerable<ValidationResult> Validate(ValidationContext      validationContext)
  {
     foreach(var result in base.Validate(validationContext).ToList())
     {
     }

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

You need to call ToList() since the base method returns IEnumerable type data

wtf512
  • 4,487
  • 9
  • 33
  • 55