Some months ago, I was developing a Silverlight application using the Entity Framework as data layer and a WCF service as the service layer. I came across a problem when doing the client validation.
Silverlight allows use of DataAnnotations which basically provides attributes classes, the ValidationException object belongs also to System.ComponentModel.DataAnnotations. This is what I want to use to do my validations.
Consider the following (and stupid) scenario:
We have a form that the user uses to add new movies in his database. The title field is required and should be between 6 and 12 characters.
We have a standard edmx file which contains a table of Movies.
We have a Silverlight-Enabled WCF Service for the Service Layer.
Our edmx file created for us the entity Movie. The definition of this object is defined in the designer file of our edmx file and this is our problem. To add some validation logic to this business object, we will need to modify this designer file meaning that whenever we will modify something in the edmx file, we will loose our modifications.
Well the Entity Framework Code-First answers this issue by allowing to define your model objects by simply writing “plain old classes” with no base classes required.
Now that you have full control on the model objects when can modify it easily and add whatever you want, validation for instance 😀
In order to use this “server-side” objects on the client, here is what you must do:
– Create a Class Library which will contains your entities, let’s call it MyMovies.Service.Entities
– Create a Silverlight Library where will will add your entites classes as link ( Add existing item, Add-> Add as link), let’s call it MyMovies.Entities
– Add a reference to this Silverlight Library in your Silverlight Project
In your WCF Service Project, add a reference to the MyMovies.Service.Entities
Use Code-First to build your DbContext using the object defines in the MyMovies.Service.Entities assembly.
In your Silvelright Project, Add a service reference to your WCF Service Project and there the magic happens.
If you look the Reference.cs file into your WCF reference, you can see that the object used in this proxy file is the MyMovies.Service.Entities files.
So here you go, you can use your validation defined in your entities.
I won’t show any code here, you can download the following project which provides a sample of what I’ve explained before.