POCO classes Validation Question RRS feed

  • Question

  • I'm developing an application consisting of: domain layer (entities, value objects, ...), infrastructure layer (entity framework 4.1 code first, ..), service layer (wcf rest as the entry point for presentation layer) and MVC 3 as the presentation layer. The Controllers call the WCF REST services.

    The validation of my ViewModels (in MVC) can be handled by using DataAnnotations, View validation can be handled by using jquery-validate plugin. DataAnnotations on my mapping files (EF 4.1)

    Question: how should I do my validation in my POCO classes? DataAnnotations or by using a Validate or GetBrokenRules method in every POCO class?

    Saturday, April 16, 2011 7:31 PM

All replies

  • If you can use DataAnnotations then I believe the recommended idea is to use a separate partial class whose role is ONLY to demark you classes properties with data annotations, via MetadataType. E.g. MetadataType(typeof(MyClassIWantValidated))]. I guess that's what you are doing already? Where do you believe you'll need validation in your classes other than during persistance/entry? Or to put it another way, somewhere where you cannot use data annotations?

    Sunday, April 17, 2011 8:05 AM
  • Thanks.

    Validation is needed, not only when persisting (= saving an object in a datastore for reuse) an object, but also when an object is instantiated (=object in memory).

    I don't use generated classes but 'hand-written' POCO classes. DDD puts validation in this POCO classes (so no partial classes, ...). I'm only confused as to whether I should use DataAnnotations or Validation methods (eg AddBrokenRule, ...) in my POCO classes. In fact this is a matter of how to implement validation in .NET.


    Sunday, April 17, 2011 8:21 AM
  • For me it's a case of can DataAnnotation provide what you need, otherwise if you have to implement the validation rules in two places that isn't ideal. In a domain object I would typically look to have an IsValid method. However that's because I'd use DataAnnotations for very simple integrity checks. Having said that it depends on the style you wish to follow. There is an argument that says that all validation in a domain object should only be simple integrity checks. If there is a business rule that spans domain objects then they're are implemented in their own business rule/or saga components. Indeed I've argued for this before whereas frameworks such as CLSA adopt the more hardcoded style you mention with AddBrokenRule. Having the rule separated is nice because it means that volatile biz rules can be changed without changing the domain objects.  It's an interesting area, and I'm pretty sure there isn't 'a' correct answer.
    Sunday, April 17, 2011 8:32 AM