I was hoping to wait for .Net 4.0 to drop before I started making a real MVC2 work application but just got the opportunity to rewrite a smaller existing web project. MVC2 for .Net 3.5 seemed a logical choice. In addition to finally getting MVC2 into a project, I wanted to try messing around with Entity Framework. Being decently skilled with LINQ-to-SQL, getting some experience with it’s successor, Entity Framework, seemed like a wise idea. After creating my models and adding some controllers and views. It was time to start testing out the new DataAnnotation validation. DataAnnotations allow you to place attributes on your entities’ properties which handle making sure they are valid. So for example, if I had an ApplicationName property that I wanted to both require, and mandate that it was no longer than 50 characters, I could do the following:
The first issue I came across had to do with Entity Framework. I can’t add these annotations to the generated code from EF. The next time I edited my model, my annotations would be overwritten. So following Scott Gu’s example, I created a buddy class.
So now, this will tell MVC that when it checks the validation on the Application object, it should check these rules. So everything should work fine right? It didn’t. For some reason, my validation was never being hit. I scoured the web. I ended up trying to add a ValidationAttribute and a DataAnnotationsModelValidator (as described by Phil Haack here). It was referewhen adding these that I started getting a compilation error saying that my reference to System.ComponentModel.DataAnnotations was not correct. I was referencing the 18.104.22.168 version when the attribute and model validator required 22.214.171.124. The data annotations and the buddy class set up did not care at all which version of the DLL was referenced, hence there was nothing to indicate this might be an issue. After switching the DLL and commenting out the ValidationAttribute and DataAnnotationsModelValidator, my validation continued to work fine. So, if you run afoul of any issues with your validation working, be sure to check your version of System.ComponentModel.DataAnnotations.