Recently Entity Framework 4.1 was released. While most people were very enthusiastic about the code first stuff, code first was the part that impressed me the least. This is because in my line of business we deal with stored procedures a lot and it turns out that mapping to stored procedures isn’t supported with code first in the 4.1 release. What did catch my eye is the new DBContext api. As you’ll probably know, the new DBContext class is largely a wrapper around the ObjectContext class with a simplified API. Now you might think as I did: “But if I’m comfortable with the ObjectContext class and I don’t use code first, why in the world would I need a DbContext?”. The answer is pretty simple. The DbContext has a feature which simply isn’t supported by the ObjectContext: data validation with the attributes from the System.ComponentModel.DataAnnotations namespace. In this article I’ll show you how to decorate your classes with validation attributes and how these classes can be reused by both the client and the server. The client will be a WPF application. If you don’t like WPF or you just don’t care, feel free the skip to the “WCF Service” paragraph. That’s where the Entity Framework 4.1 part is explained.
Let’s first start with the two projects that are responsible for my data access classes, including the entities:
Both DbContextLibrary and EntitiesLibrary are normal class library projects. I started with the DBContextLibrary and used the new “DbContext Generator” T4 template to generate classes. When you use this template you’ll actually get two T4 templates added to your project. The one with “.Context” in it generates your DbContext class, the other one generates POCO entities. I’ve simply moved the one that generates the entities to it’s own class library. If you do this, you’ll have to add a namespace in the T4 template that generates the DbContext, so that DbContext knows the entity classes. In this article I will only have one entity, namely Product. I’ve added some validation to this class using the buddy class mechanism. This code is contained in the Product.Metadata.cs file in the EntitiesLibrary project:
You can see that I’ve only added validation for the ListPrice property using the Range attribute. Now let’s take a look at the Adventureworks2008.tt T4 template, since it contains some stuff I had to manually edit:
In order for entities to support automatic validation in WPF I had to change the following things in this template:
- Line 10: The path to the .edmx file. The .edmx is contained in another project and the T4 template by default assumes it’s in the same project as the T4 template, so you’ll need to adjust this.
- Lines 24-27: I’ve added these namespaces because they are necessary for the the rest of my code.
- Line 29: I’ve changed this line to let my entity implement the IDataErrorInfo interface. You have to understand that in WPF, unlike in Silverlight, the data annotations aren’t automatically read by the components (DataGrid). You’ll have to implement the IDataErrorInfo interface and validate manually using the data annotations.
- Line 49-82: These are the members you’ll have to implement because of the IDataErrorInfo interface: Error and an indexer. Normally, in the Error property you’ll write code to validate the whole object and construct a string with an error message. In the indexer you’ll write code that validates a single property. The property name is supplied as an argument and you’ll need to construct a string with an error message. In both members I’ve used the Validator class to validate. Whenever you are in a situation that you’ll need to validate using data annotations and this doesn’t happen automatically, you can use the static Validator class to do the validation for you. This isn’t difficult, it’s just something to keep in mind. To make the validation generic for property validation, you’ll have to supply the member name like on line 72. Next to that, you’ll have to use some reflection to get the property value in a generic way. This reflection code is found on line 73, it’s the first argument of the TryValidatePropertyMethod.
- Line 31-47: I’ve intentionally covered lines 49-82 first. Because now it’s clear that I implement the IDataErrorInfo interface in my entity and I use the Validator class to do the validation for me. If you now create a list of Products, add those to a WPF datagrid and use TwoWay binding with validation enabled for the ListPrice, you would think that validation should kick in. This was at least what I thought. Turns out that the whole buddy metadata mechanism isn’t something that’s supported by the static Validator class. It are the frameworks like WCF RIA Services that add support for the buddy mechanism. Luckily with some googling and reflectoring I came to the conclusion that the Validator class uses .Net’s extensible TypeDescriptor mechanism instead of reflection, which can be seen as a mechanism similar to reflection, only the type information can be extended runtime. I had to extend the type information once for each entity that get’s generated, with the information in the buddy metadata class. I can’t do this in the constructor, because then it would happen way to often. A static constructor seemed a good place to me. The declaration of the static constructor is found on line 31. On line 36 I use the MethodBase class to get a reference to the current type. This is needed since I need to extend the type information of the current type. On line 37-39 I check whether the MetadataTypeAttribute is present. If so, I retrieve it on line 41. This attribute has the property “MetadataClassType”. This property contains the type you supply when you place the MetadataType attribute. On line 42 I extend the type information of the current type with the associated metadata. I do this by calling the AddProviderTransparent method on the TypeDescriptor class and supplying an AssociatedMetadataTypeTypeDescriptionProvider. This provider is used for the buddy class mechanism and it’s constructor takes two arguments. First is the type you wish to extend with extra metadata, second is the metadata class.
So know we have a T4 template, that generates entities with support for WPF validation using data annotations and the buddy mechanism. Of course you can use the generated entities for any technology that doesn’t use the data annotations by default.
The WPF Application
The article is getting quite long, so bare with me :). Luckily, this paragraph will be short. Here is the XAML:
The most important part is on line 20. The binding for the ListPrice property is set to TwoWay, ValidatesOnDataErrors is true and NotifyOnValidationError is also true. This will make sure that when the user enters a listprice smaller than zero, validation will kick in:
The WCF Service
Last up is the WCF Service, which uses the new EF 4.1 DbContext api to load from- and update data in the database:
- Line 19-25: This isn’t that exciting, I just load the data with no tracking from the database. In a service, tracking won’t do you any good.
- Line 29-55: This is the most interesting part. My web project also references my EntitiesLibrary project, witch contains the Product class with the buddy mechanism and the data annotation on the listprice. The DbContext api will by default automatically validate before saving and will throw an exception if there are errors. I’m disabling this behavior on line 34 since I’m going to validate up front. Because I’m in a service, the DbContext can’t detect any changes since it doesn’t have any original values, so I’m also disabling this behavior on line 37. On line 39 the product is attached. On line 40-41 I’m changing the state of the product to modified. This is necessary, if you forget this, the DbContext won’t validate (even when doing this manually) or save the product. Since I know for certain that the DbContext is only tracking one entity, I retrieve the single DbEntityValidationResult on line 42. If there are no errors, I will get an empty collection and because of the SingleOrDefault method I will get null. Thus, if the error is not null on line 43, I throw a new FaultException and supply it with a string. This string contains the validation errors for all the properties that caused errors. Of course, this will only be the listprice since it’s the only one with a data annotation. If the validation returned null, I’m saving the changes on line 52.
The Console Application
As you can see above, using the DbContext api means that you don’t have to write validation code on both the client and the server. This problem was already solved for Silverlight by WCF RIA Services, but now we can finally share the data annotations between the server and other client technologies as well. Now let’s test our service with a client that doesn’t do any validation in the UI and tries to submit some illegal values:
If you’d run the application above you would get the following output:
And we can see that our server is protected against bad input.
One of the most overlooked features of the Entity Framework 4.1 is the new ability to validate the entities according to the buddy class mechanism and data annotations. This means that when we write serverside code, we don’t have to write the validation logic ourselves and that we can share the entities between client and server to use the same validation logic on the client. This also works of course when the client is an ASP.NET MVC Controller for example.
I’ve tried to share code this way between a Silverlight client and a WCF Service but this doesn’t work. This is because the EntitiesLibrary project must be a Silverlight class library before it can be referenced by both Silverlight and the server project. In Silverlight the data annotations are defined in a different assembly with a different version than the data annotations in the full .Net framework. The Entity Framework and the Validator class in the full .Net framework will NOT recognize data annotations from Silverlight. It seems that the best way to share validation code with Silverlight is by using WCF RIA Services. You can find the working example here.