More rant on data validations for Silverlight applications using RIA
Models in Silverlight can be validated in three ways (atleast):
- Data Annotations
- IDataErrorInfo
- INotifyDataErrorInfo
Data Annotations are attributes attached to the model properties. Each of the attributes have a IsValid() method which fire an exception if validation fails. Because the validation logic is based on exceptions, it does not offer good performance - especially, if the model contains a lot of properties, all failing exceptions.
IDataErrorInfo attempts to use an indexer to retrieve the validation error for a model property. IDataErrorInfo is simplistic - Only one error per property, and the error message can only be a simple string.
INotifyDataErrorInfo is Silverlight 4 way of handling validations. It can handle multiple errors per property and allows complex classes to be returned as error objects. It also notifies the UI that there is an error on the property. In this way, checks can be done async on the server, eg duplicate name checks.
How does RIA handle validations? When a DomainService is created, a DomainService.metadata.cs file is created. This file contains a partial <Entity> class which defines the metadata for the Entity. (Entity framework emits the other partial <Entity> class with data mappings and Key / Constraint information). This metadata class is where we can define the data annotations.
When we do a build of the Silverlight project, the metadata information from the RIA (with validation attributes) is combined with the entity class from the Entity framework to create a new <Entity> class within the Silverlight application. What is troublesome is that the <Entity> class derives from an abstract Entity base class which implements a lot of interfaces including INotifyDataErrorInfo. In my opinion, the auto-generated code is messy from a design view point. The auto-generated Silverlight <Entity> class has the same type name as the <Entity> class in the server side but a completely different implementation.
In my opinion, the validations using RIA is messy. I understand that we have to do validations both on the Silverlight end as well as the RIA service end. (Or am I mistaken?) I am not sure if the different approaches using INotifyDataErrorInfo and IDataErrorInfo are built to take care of this. In any case, with RIA, Data annotations seems to be the way to go.
But again, I am still exploring.
Category : Silverlight