Search code examples
c#entity-frameworkdata-annotationsn-tier-architectureclient-side-validation

Displaying Data Annotation Error Messages in WinForms Using N-Tier Entity Framework


Please note that I am using N-Tier Entity Framework (http://ntieref.codeplex.com/) with (WCF) SmartClient Winforms application. Using Data Annotations to perform client side validation, I would like to (mimic MVC) choose to immediately display a Data Annotation Error Message to the User when they type in a value, and/or choose to wait to display all the Error Messages for all the Entity Properties when the User clicks the save button (possibly using Validator.TryValidateObject), but prior to calling context.SaveChanges().

Currently, when the property value changes and the User attempts to change control focus, the Entity OnPropertyChanging() method executes, the property is checked for validation (ValidateProperty()) and if it fails validation (due to a Data Annotation) an exception is thrown and the control will not lose focus, but no exception/error message is passed/displayed.

How can I get the Data Annotation Error Messages available for client side validation?

@ChristofSenn Do you have any suggestions?


Solution

  • N-Tier Entity Framework provides multiple validation mechanisms:

    1. Early validation performed while setting a property value, throws if invalid and prevents actually setting invalid values (this is enabled by default)
    2. IDataErrorInfo lets you validate a property's current value (requires IsValidationEnabled=false to be able to actually set invalid on properties)
    3. ValidateProperty(string propertyName, object value) allows validating values without actually trying to apply the value to the property.

    In your case I presume you need to set IsValidationEnabled=false as othervise WinForms DataBinding fails to set invalid values in the first place and then doesn't get back any validation error using IDataErrorInfo interface, since the value wasn't actually set. The property IsValidationEnabled is available on DataContext, EntitySet, and Entity level.