If you use NHibernate with MySQL and Linq 2 NHibernate to simplify fetching data you may face with problem: queries created by Linq2NH use square brackets by default. That is fine for SQL Server but won't work in MySQL which uses backticks ``.
For MySQL we need to instruct NHibernate to use backticks instead of square brackets. It can be done by setting interceptor in NH config:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public class NHConfiguration { public static Configuration Build( string connStr) { var config = Fluently.Configure() .Database( MySQLConfiguration.Standard .ConnectionString(connStr) .AdoNetBatchSize(100) .DoNot.ShowSql() ) .Mappings(cfg => { // add mappings }) .ExposeConfiguration(x => { with backticks for MySQL x.SetInterceptor( new ReplaceBracesWithBackticksInterceptor()); }); return config.BuildConfiguration(); } } |
in its OnPrepareStatement method we just replace square brackets with backticks:
1 2 3 4 5 6 7 | public class ReplaceBracesWithBackticksInterceptor : EmptyInterceptor { public override NHibernate.SqlCommand.SqlString OnPrepareStatement(NHibernate.SqlCommand.SqlString sql) { return sql.Replace( "[" , "`" ).Replace( "]" , "`" ); } } |
After that Linq2NH will start working in MySQL.
No comments:
Post a Comment