开发者

NHibernate.Validator vs DataAnnotations

开发者 https://www.devze.com 2023-01-06 18:14 出处:网络
In my APS.NET MVC project I\'m using DataAnnotations for validations. I moved from L2S to NHibernate orm and in fact found that NHibernate has its own validator (NHibernate.Validator)

In my APS.NET MVC project I'm using DataAnnotations for validations.

I moved from L2S to NHibernate orm and in fact found that NHibernate has its own validator (NHibernate.Validator)

Does it make sense to move to NHibernate.Validator as well?

For example DataAnnotations has [Required] attribute and NHibernate.Validator [NotEmpty, NotNull, NotNullNotEmpt开发者_开发技巧y] and it makes me think what to use.


I've used both in production projects and, if you have the time to make the switch, I would highly reccomend NHibernate.Validator for a couple of reasons:

  1. NHibernate.Validators has a richer set of validation attributes (for example, the handful you mention above)
  2. If implemented properly, NHibernate.Validators validations are easier to unit test.

No. 1 wasn't huge for me, and may not be for you, as the set of attributes in DataAnnotations is pretty complete (and you can fall back to RegEx, if need be), but no. 2 was a big deal for me because I wanted to be able to include data validation as a part of my Domain Model unit tests, as opposed to testing those only through UI/Web testing via WatiN or Selenium. Using Validators also allowed me to mix Domain Model rule validation (Property X OR Y must have a value, but both cannot be null) without having to go to another place to do so.

For some basic guidance on using NHibernate Validators, check out this article: http://nhibernate.info/blog/2009/04/02/nhibernate-validator-and-asp-net-mvc.html, and I would also reccomend getting the source for S#arp Architecture, Billy McCafferty's great framework for creating DDD-style ASP.NET MVC applications. In particular, check out his implementation of Validators and the Validator ModelBinder you'll need to create to transfer NHibernate validation errors into MVC ModelErrors. Download the S#arpArchitecture source here: http://github.com/codai/Sharp-Architecture.

The bottom line is this: Using NHibernate.Validators is the more extensible, testable option, but it will take some doing for you to use it properly. DataAnnotations is baked into the framework and easier to get running with, there's no question about that.

Hope that helps.

0

精彩评论

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