Is there a way to enforce a minimum string length with NHibernate?
I have a string property on an entity that I would like to mark as required. For example,
public class Product
{
public virtual string Name { get; set; }
}
In my mappings, I can declare Name
as required (using Fluent NHibernate):
mapping.Map(x => x.Name).Required();
However, this only restricts t开发者_如何学Che string from being null
. If I assign it to String.Empty
, NHibernate will happily store the value of ""
into the database.
My question is, is there a way of enforcing a minimum length for strings? For example, in this case, a product name should be at least 3 characters. Or will my business logic need to handle this instead of NHibernate?
Using the NHibernate validator:
public class Product
{
[Length(Min=3,Max=255,Message="Oh noes!")]
public virtual string Name { get; set; }
}
I believe you can only enforce the maximum length and nullability with NHibernate (with or without Fluent).
The minimum length can be enforced with a custom DataAnnotation at your model (or ViewModel if you use MVC and don't want to bloat your domain model with attributes)
This is not the responsibility of (Fluent)NHibernate, it's the responsibility of a validation library. For example, check out NHibernate Validator.
精彩评论