I am writing an ASP.NET MVC 2 application using NHibernate and repository pattern. I have an assembly that contains my model (business entities), moreover in my web project I want to use flattened objects (possibly with additional properties/logic) as ViewModels. These VMs contain UI-specific metadata (eg. DisplayAttribute used by Html.LabelFor() method).
The problem is that I don't know how to implement validation so that I don't repeat myself throughout various tiers (specifically validation rules are written once in Model and propagated to ViewModel).
I am using DataAnnotations on my ViewModel but this means no validation rules are imposed on the Model itself. One approach I am considering is deriving ViewModel objects from business entities adding new properties/overriding old ones, thus preserving validation metadata between the two however this is an ugly workaround.
I have seen Automapper 开发者_如何学Pythonproject which helps to map properties, but I am not sure if it can handle ASP.NET MVC 2 validation metadata properly. Is it difficult to use custom validation framework in asp.net mvc 2?
Do you have any patterns that help to preserve DRY in regard to validation?
It is fine to repeat validation. Trick is to place it where it's appropriate.
In your case - at UI, validate UI logic (view model props must not be null, in correct format etc.), in business layer - validate business logic (account has money etc.).
Do not use DRY as an excuse to violate SRP! :P
View models are supposed to uncouple your business layer from presentation role.
Don't glue everything together again.
I guess Automapper can't handle that. :)
精彩评论