Fluent NHibernate with System.ComponentModel.DataAnnotations

So I’m building a product with NHibernate and possibly another ORM. The main focus of the app is a ASP.NET MVC 2.0 web application. So I, obviously, want the built in validation client-side in JavaScript and server side. By default, the MVC stuff uses the System.ComponentModel.DataAnnotations attributes to validate properties on your domain.

What I REALLY wanted was to use the Data Annotations with Fluent NHibernate for my DB mapping files. This presents a problem, right? WRONG! Because Fluent NHibernate is so extensible, I can easily create a convention to use the Attributes. Then all I have to do is add the convention to my Fluent NHibernate AutoMapper instance and the properties with the attributes are just taken care of. Isn’t that neat!!

Required is a common notion with domains. Something HAS to be defined for an entity to be considered a reputable entry. Here’s the convention to use the Required attribute in Fluent NHibernate.

 

Code Snippet
using System.ComponentModel.DataAnnotations;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;

namespace Data.NHibernate.Conventions
{
    public class RequiredConvention : AttributePropertyConvention<RequiredAttribute>
    {
        protected override void Apply(RequiredAttribute attribute, IPropertyInstance instance)
        {
            instance.Not.Nullable();
        }
    }
}

 

 

As you can see… there’s really only 1 line of code!

 

I just showed you one out of the handful of attributes in the DataAnnotations library. To use the other attributes, you just basically follow the same basic outline of the example above. Not bad, eh :)



kick it on DotNetKicks.com
Published Friday, October 23, 2009 4:34 PM by zowens

Comments

No Comments