Validate properties from base class in derived class by metadata

Topics: Validation Application Block
Jul 10, 2013 at 4:23 PM
Edited Jul 10, 2013 at 6:20 PM
Hello!
I've got some problem using metadata validation.
I have some base class:
public class BaseClass
{
public string Name {get; set;}
}
And derived class:
[MetadataType(typeof(DerivedClassMetadata))]
public class DerivedClass: BaseClass
{
public string Label {get; set;}
}
Metadata class will look like this:
public class DerivedClassMetadata
{
[NotNullValidator]
public string Name {get; set;}
}
So in this case validation is not working when I try to validate DerivedClass, but works if I write metadata attribute on BaseClass.
How can I solve this problem writing metadata on DerivedClass?

I'm using Entlib 5.0
Editor
Jul 11, 2013 at 5:41 AM
You can place the MetadataType on the base class:
    [MetadataType(typeof(BaseClassMetadata))]
    public class BaseClass
    {
        public string Name { get; set; }
    }

    public class BaseClassMetadata
    {
        [NotNullValidator]
        public string Name { get; set; }
    }

    [MetadataType(typeof(DerivedClassMetadata))]
    public class DerivedClass : BaseClass
    {
        public string Label { get; set; }
    }

    public class DerivedClassMetadata : BaseClass
    {
        [NotNullValidator]
        public string Label { get; set; }
    }
If you want to have specific validation for each derived type then you can override BaseClass properties:
    public class BaseClass
    {
        public virtual string Name { get; set; }
    }

    [MetadataType(typeof(DerivedClassMetadata))]
    public class DerivedClass : BaseClass
    {
        public override string Name { get; set; }
        public string Label { get; set; }
    }

    public class DerivedClassMetadata 
    {
        [NotNullValidator]
        public string Name { get; set; }
    }

Another alternative would be to use XML configuration (which doesn't support inheritance) to specify the explicit validation for each derived type.

~~
Randy Levy
entlib.support@live.com
Enterprise Library support engineer
Support How-to
Jul 23, 2013 at 6:40 PM
Thank you for reply. We`ll think on this situation...