9

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.

LeftyX
  • 35,328
  • 21
  • 132
  • 193

1 Answers1

13

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);
    }
}
LeftyX
  • 35,328
  • 21
  • 132
  • 193
  • 1
    Thank you so much for this. I've spent all day wading through NHibernate and Fluent.Nhibernate code trying to work out why my fluently mapped .CustomSqlType("AnsiString") still seemed to spit out an NVarchar to sql server. It kinda makes me wonder what the point of CustomSqlType is. – zeocrash Jul 22 '19 at 18:33