Force validation of RIA entities

Force validation of RIA entities

As I am currently developing a Silverlight Application using RIA Services (and Prism), I ran into some little tricks that can really help the developer’s life.

One of the common needs is to force the validation of all fields of an exposed entity in one time, and not just one field just after it has been updated.
This is very important especially when you want to insure our object is strictly validated before submitting changes.

The trick is to create a ValidationContext and manually validate the whole object. The thing to be careful of is not to forget to update the ValidationErrors list of the entity.

public static void Validate(this Entity entity)
// prepare the result
var validationResults = new List<ValidationResult>();
// create a validation context
var validationContext = new ValidationContext(entity, null, null);
// validate
Validator.TryValidateObject(entity, validationContext, validationResults);
// reset the validation errors of the entity
foreach (var error in validationResults)

As you can see, I made this method as an extension to the Entity type. So that you can easily use it on every entity you have.