Data Annotations validation Built into model
- by Josh
I want to build an object model that automatically wires in validation when I attempt to save an object. I am using DataAnnotations for my validation, and it all works well, but I think my inheritance is whacked. I am looking here for some guidance on a better way to wire in my validation.
So, to build in validation I have this interface
public interface IValidatable
{
bool IsValid { get; }
ValidationResponse ValidationResults { get; }
void Validate();
}
Then, I have a base class that all my objects inherit from. I did a class because I wanted to wire in the validation calls automatically. The issue is that the validation has to know the type of the class is it validating. So I use Generics like so.
public class CoreObjectBase<T> : IValidatable where T : CoreObjectBase<T>
{
#region IValidatable Members
public virtual bool IsValid
{
get
{
// First, check rules that always apply to this type
var result = new Validator<T>().Validate((T)this);
// return false if any violations occurred
return !result.HasViolations;
}
}
public virtual ValidationResponse ValidationResults
{
get
{
var result = new Validator<T>().Validate((T)this);
return result;
}
}
public virtual void Validate()
{
// First, check rules that always apply to this type
var result = new Validator<T>().Validate((T)this);
// throw error if any violations were detected
if (result.HasViolations)
throw new RulesException(result.Errors);
}
#endregion
}
So, I have this circular inheritance statement. My classes look like this then:
public class MyClass : CoreObjectBase<MyClass>
{
}
But the problem occurs when I have a more complicated model. Because I can only inherit from one class, when I have a situation where inheritance makes sense I believe the child classes won't have validation on their properties.
public class Parent : CoreObjectBase<Parent>
{
//properties validated
}
public class Child : Parent
{
//properties not validated?
}
I haven't really tested the validation in these cases yet, but I am pretty sure that anything in child with a data annotation on it will not be automatically validated when I call Child.Validate(); due to the way the inheritance is configured. Is there a better way to do this?