开发者

Domain object validation vs view model validation

I am using ASP.NET MVC 3 and I am using FluentValidation to validate my view models. I am just a little concerned that I might not be on the correct track. As far as what I know, model validation should be done on the domain object. Now with MVC you might have multiple view models that are similar that needs validation. What happens if a property from a domain object occurs in more than one view model? Now you are validating the same property twice, and they might not even be in sync. So if I have a User domain object then I would like to 开发者_如何学Godo validation on this object. Now what happens if I have UserAViewModel and UserBViewModel, so now it is multiple validations that needs to be done.

In my News class I have a property called Title, which is a required field. On my view model I also have a Title property, I use AutoMapper to map the News and NewsViewModel. So this validation is happening twice. When does domain model validation occur and when does view model validation occur?

The scenario above is just an example, so please don't critise on it.


It's a subtle distinction but the validation on your view model is to validate correct user input and forms an anti-corruption layer for your domain model, whereas the "validation" on your domain model enforces business rules. It is perfectly normal and you should have validation on both layers. In fact it may be feasible that UserAViewModel has slightly different input validation from UserBViewModel. As for your question, generally I try to avoid exposing domain objects through my ViewModel and instead map between them (often using something like AutoMapper), that way your ViewModels truly are anticorruption layers rather than property bags of domain models. Hope that helps.


What happens if a property from a domain object occurs in more than one view model?

This shouldn't happen. View models should be totally divorced from your domain.

Does this answer your question?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜