Tutorial :Can I get NHibernate to enforce that a string property is non-empty?



Question:

I know about the not-null attribute. Is there one for enforcing the minimum length of a string property? I don't want empty strings in my database.


Solution:1

I don't know of anything in the mapping file that will let you do this (and I don't see anything in the schema). You could probably define a custom type using NHibernate.IUserType and build your logic into that type (if the string is empty save null). Here is an example of building an IUserType (it would be easy to change this example code to work for you)

The other option is to take advantage of NHibernate.Validations and to handle the validation logic before getting to the point where you are saving the entity to the database.


Solution:2

You are looking for NHibernate Validator! There's a blog post here showing some of its goodness.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »