views:

36

answers:

3

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 the 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?

+1  A: 

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)

Raphael
+1  A: 

This is not the responsibility of (Fluent)NHibernate, it's the responsibility of a validation library. For example, check out NHibernate Validator.

Mauricio Scheffer
+1  A: 

Using the NHibernate validator:

public class Product
{
    [Length(Min=3,Max=255,Message="Oh noes!")]
    public virtual string Name { get; set; }
}
Rafael Belliard
Marked as the answer for `Oh noes!` :).
Daniel T.