asp.net-mvcasp.net-mvc-2data-annotationsasp.net-mvc-validation

ASP.NET MVC 2 Validation: Metadatatype can't be added to standard POCO CLR classes - what's an alternative?


I am using Entity Framework and generating my POCO classes via T4 - these classes inherit from nothing and are very plain and simple (created via template in vs 2010)

I tried using the Metadatatype Attribute so I could create a buddy class but when I did this I no longer was able to see my properties... if I removed the attribute! the properties appeared.

Anyway, searching deeper I found this statement from Microsoft

The associated class must be used with EDM or LINQ-to-SQL models because CLR types cannot mark existing properties with new attributes. If you are working with CLR objects directly, sometimes referred to as Plain Old CLR Object (POCO) types, you can apply the attributes directly to the model

So it appears it doesn't work. Anyway it's difficult for me to insert my Data Annotation on the MODEL itself because it's created via T4 hence if I edit it and then re-run the tool it will remove all my changes.


Solution

  • There is a pretty strong consensus around SO and the MVC blogosphere that you shouldn't annotate your business/crud/domain classes with attributes. Not only is your entire MVC stack becoming dependent upon your business/database classes but you'll quickly end up with multiple context scenarios ( same Model, different validation rules ) that are impossible to validate with just a single model.

    Use separate view models for your screens, annotate those.


    Based on your comment: "Data Annotation on the MODEL itself because its created via T4 hence"

    What I'm trying to say is put your dataannotations on your viewmodels, leave your POCO models alone.