RIA services solves for you a lot of problems and one of them is to add validations rules on the entities both on the client and on the server side. These differents rules are checked when you submit the changes from the client to the server or when you call “EndEdit” on the entities.


But there is times when you want to leverage the validation without submit the changes or commit your object modification (in a IEditableObject way of talking). In this post we will discover how to do just this.



Why don’t just call EndEdit() by the way ? Because by doing so you may push entities which are in a wrong state into the domain context with no way to revert to a correct state. Indeed, although the EndEdit method of the RIA entities launch the validation process and update the validations errors it does not stop the EndEdit from being performed even if there is errors.

So it may be a better idea to check if the Entity is in a correct state (no validation errors) before to call the EndEdit.


The little snippet to use is very simple and straightforward and it works well with the Silverlight toolkit dataform (if needed). It use the Validator class from the same assembly in which are the differents validations sttributes : System.ComponentModel.DataAnnotations.


/// <summary>
/// Validates the item and add its error in its validationErrors list.
/// </summary>
/// <param name="dataToValidate">The data to validate.</param>
/// <returns><code>True</code> if the object is valid, false otherwise.</returns>
public static bool ValidateItem(Entity dataToValidate, 
      out ICollection<ValidationResult> validationResults)
  if (dataToValidate == null) 
     throw new ArgumentNullException("dataToValidate");
  validationResults = new List<ValidationResult>();
  ValidationContext context = new ValidationContext(dataToValidate, null, null);
  Validator.TryValidateObject(dataToValidate, context, validationResults, true);
  foreach (var res in validationResults)
  return validationResults.Count == 0;


Do you know any other way to perform this ?

Shout it kick it on DotNetKicks.com