Silverlight and RIA services – overriding an attribute set in a base class.

Recently I found myself in the following situation. I had let’s say this class: DerivedClass inheriting from a BaseClass on the server side of things.

One of the properties of the BaseClass has the [Required] attribute applied.

public class BaseClass{

[Required]
public string Name { get; set; }

}

It just happen that in my DerivedClass I needed some more validation to be done so I would like to go for a [CustomValidation] attribute with its own custom validation method. More, I don’t need the constraint of the [Required] attribute anymore (if you remember the [Required] attribute, by default, implies the property should not have an empty or null value) so I want to revert its effect.

You can write the following code:

using System.ComponentModel.DataAnnotations

[MetadataType(typeof(DerivedClassMetaData)]
public class DerivedClass : BaseClass{

}

public class DerivedClassMetaData{

[Required(AllowEmptyStrings=true)]
[CustomValidation(typeof(SomeValidationClass), “ValidationMethod”)]
public string Name{ get; set; }

}

public class SomeValidationClass{

public static ValidationResult ValidationMethod(object value, ValidationContext validationContext){
}
}

The most important thing in the code above is the [MetadataType] attribute which is basically allowing me to attach meta data type to my derived class and basically readjusting some of its inherited attributes. One thing I did was to redefine the [Required] attribute to undo the effect of the similar definition on the BaseClass. Secondly I attached a custom validation to the Name property.
A very good resource on custom validation is
here.

On the client side, in the code generated the Name property looks like this:

[System.ComponentModel.DataAnnotations.CustomValidationAttibute(typeof(SomeValidationClass), @”ValidationMethod”)]
[System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings=true)]
public string Name{

}

The whole SomeValidationClass code is brought over from the business side and included in the generated code so the CustomValidationAttribute can find its arguments.

Cheers.

Advertisements