Search code examples
nhibernatefluent-nhibernateconventionsnvarchar

FluentNHibernate and VARCHAR Columns


I am starting a simple .NET project with FluentNhibernate.
I've followed few examples I've found on the Internet and it seems quite easy to grasp.
I've realized that if I let FluentNhibernate build my DB schema (Sql Server 2000) it generates NVARCHAR fields for my strings model properties.

Someone suggested that I can add a convention to change the type.

This bit of code works great:

public class AnsiStringConvention : IPropertyConvention 
        {
            private static Type stringType = typeof(string);
            public void Apply(FluentNHibernate.Conventions.Instances.IPropertyInstance instance)
            {
                if (instance.Property.PropertyType == stringType)
                {
                    instance.CustomType("AnsiString");
                }
            }
        }

Now my DB fields are VARCHAR, as I expected.
I needed to add a component to my class, following the DDD pattern I've put the Address in a separate class and added it to my Customer class.
I've created a separate mapping file for the address:

public class AddressMap : ComponentMap<Address>
{
    public AddressMap()
    {
        Map(x => x.Number);
        Map(x => x.Street)
            .Length(100);
        Map(x => x.City)
            .Length(50);
        Map(x => x.PostCode)
            .Length(5);
    }
}

Now, all the fields of my Customer table are VARCHAR but the fields of the Address (Street, City and PostCode) component are still created as NVARCHAR.


Solution

  • Found a solution defining AnsiString as CustomType:

    public class AddressMap : ComponentMap<Address>
    {
        public AddressMap()
        {
            // this.Map(x => x.Number);
            this.Map(x => x.Street)
                .CustomType("AnsiString") 
                .Length(100);
            this.Map(x => x.City)
                .CustomType("AnsiString")
                .Length(30);
            this.Map(x => x.State)
                .CustomType("AnsiString")
                .Length(20);
            this.Map(x => x.PostalCode)
                .CustomType("AnsiString")
                .Length(10);
            this.Map(x => x.Country)
                .CustomType("AnsiString")
                .Length(40);
        }
    }