Feed Subscribe
Exception has been thrown by the target of an invocation.

NHibernate lowercase and underscore automap convention

by ondrejsv 20. February 2011 00:26

Today just a small snippet of code. If you unlucky one inherited some brownfield database with awkward lowercase_and_underscores naming convention (I really hate it):


and you are using NHibernate with Fluent automapping configuration, just use this property convention:

private class ColumnConvention : IPropertyConvention { public void Apply(FluentNHibernate.Conventions.Instances.IPropertyInstance instance) { var regexString = @"([A-Z][\w^[A-Z]]*)([A-Z][\w^[A-Z]]*)*"; var newName = Regex.Replace(instance.Name, regexString, (m => (m.Index != 0 ? "_" : "") + m.Value.ToLower())); instance.Column(newName); } }

Of course, the real gem here is the regex itself (days without writing regexes are awesome).

If you forgot how to apply a custom convention, here you go:

SessionFactory = Fluently.Configure().Database( MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("SugarCrmDb"))). Mappings( m => m.AutoMappings.Add(AutoMap. AssemblyOf(cfg). Override(am => am.Table("accounts")). Conventions.Add(new ColumnConvention()) ) ). BuildSessionFactory();
If you really don’t know what is this all about, take a read here.