I am using ASP.NET MVC with Entity Framework POCO classes and the FluentValidation framework. It is working well, and the validation is happening as it should (as if I were using DataAnnotations). I have even gotten client-side validation working. And I'm pretty pleased with it.
Since this is a test application I am writing just to see if I can get new technologies working together (and learn them along the way), I am now ready to experiment with using ViewModels instead of just passing the actual Model to the view. I'm planning on using something like AutoMapper in my service to do the mapping ba开发者_运维知识库ck and forth from Model to ViewModel but I have a question first.
How is this going to affect my validation? Should my validation classes (written using FluentValidation) be written against the ViewModel instead of the Model? Or does it need to happen in both places? One of the big deals about DataAnnotations (and FluentValidation) was that you could have validation in one place that would work "everywhere". And it fulfills that promise (mostly), but if I start using ViewModels, don't I lose that ability and have to go back to putting validation in two places?
Or am I just thinking about it wrong?
Or am I just thinking about it wrong?
Probably ;)
If you add all the validation code to your ViewModels you'd just be validating them instead of your actual Models. All your really changing is which objects can enter an invalid state.
Right now I'm happy as pie only validating ViewModels and then passing that information back to the actual Models and DAO layers. Whether or not your domain can enter an invalid state is a contentious topic though but so far this technique is working great for me. Validation in one place and no invalid objects in my persistence store.
精彩评论