In a previous post I mentioned we were using PostgreSQL together with Entity Framework Core. One of the things I stumbled over when trying to use NHibernate instead was that Entity Framework Core uses Pascal Casing to generate the names of Tables, Columns and queries whereas NHibernate uses lowercasing(which is in fact more suitable for PostgreSQL, but that is another discussion).
One of the reasons I like NHibernate so much is that it is fully customizable and that we can easily change the naming strategy to take the EF Core conventions into account.
- Start by creating a custom naming strategy:
- As a second step, register this naming strategy on your NHibernate configuration object(in this example through Fluent NHibernate):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PostgreSqlNamingStrategy : INamingStrategy | |
{ | |
public string ClassToTableName(string className) | |
{ | |
return DoubleQuote(className); | |
} | |
public string PropertyToColumnName(string propertyName) | |
{ | |
return DoubleQuote(propertyName); | |
} | |
public string TableName(string tableName) | |
{ | |
return DoubleQuote(tableName); | |
} | |
public string ColumnName(string columnName) | |
{ | |
return DoubleQuote(columnName); | |
} | |
public string PropertyToTableName(string className, | |
string propertyName) | |
{ | |
return DoubleQuote(propertyName); | |
} | |
public string LogicalColumnName(string columnName, | |
string propertyName) | |
{ | |
return String.IsNullOrWhiteSpace(columnName) ? | |
DoubleQuote(propertyName) : | |
DoubleQuote(columnName); | |
} | |
private static string DoubleQuote(string raw) | |
{ | |
raw = raw.Replace("`", ""); | |
return String.Format("\"{0}\"", raw); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static ISessionFactory CreateSessionFactory() | |
{ | |
var rawConfig = new NHibernate.Cfg.Configuration(); | |
rawConfig.SetNamingStrategy(new PostgreSqlNamingStrategy()); | |
return Fluently.Configure(rawConfig) | |
.Database(PostgreSQLConfiguration.Standard | |
.ConnectionString("<connection string>") | |
.Dialect<PostgreSQL82Dialect>().ShowSql()) | |
.Mappings(m => | |
m.FluentMappings.AddFromAssemblyOf<Program>()) | |
.BuildSessionFactory(); | |
} |