Fluent NHibernate Custom SQL Types

When mapping data types from SQL server into Fluent NHibernate, the generic mappings work just fine (as long as the data in the field fits the type declared).  In other words, a char(50), a text or a varchar(max) field in SQL server will fit in a string type without an issue.  There is one problem that can occur if you’re attempting to unit (i.e. integration) test a database and you use the SchemaExport.Create() method to generate your tables.  In this instance you’re attempting to map a string into something that the mapper will guess at.  To get it in the type that matches your database, you can declare the SQL server field type in your mappings.

Here’s an example table for storing information about a store (I’ve used this table in previous blog posts):

public class StoreMap : ClassMap<Store>
    public StoreMap()
        Id(u => u.id);
        Map(u => u.Name).CustomSqlType(“char(50)“).Length(50).Nullable();
        Map(u => u.Address).CustomSqlType(“char(50)“).Length(50).Nullable();
        Map(u => u.City).CustomSqlType(“char(50)“).Length(50).Nullable();
        Map(u => u.State).CustomSqlType(“char(50)“).Length(50).Nullable();
        Map(u => u.Zip).CustomSqlType(“char(10)“).Length(10).Nullable();

You can use any of the mapping types listed here.  I have also successfully used many of the data types that SQL uses such as “money”, “text” and “varchar”.


Leave a Reply