Modifying the SQL generated by NHibernate

Is it possible to modify the SQL generated by NHibernate? Yes:

public class BadInterceptor : EmptyInterceptor, IInterceptor {
 SqlString IInterceptor.OnPrepareStatement(SqlString sql) {
  return doHorribleThingsToSqlString(sql);            
 }
 private SqlString doHorribleThingsToSqlString(SqlString sql) { ... }
}

protected static readonly ISessionFactory SessionFactory = initialiseSessionFactory();
private static ISessionFactory initialiseSessionFactory() {
 var config = new Configuration();
 config.AddAssembly(Assembly.GetExecutingAssembly());
 config.SetInterceptor(new BadInterceptor());
 return config.BuildSessionFactory();
}

Now don’t! :) Seriously, it’s evil.

If anyone knows a nice way to get NHibernate to add some custom SQL as part of it’s SQL generation process, rather than this brute-force approach, then please let me know. I was initially playing around with this code to add some calls to SQL Server’s binary_checksum() function when loading and saving entities, and I’d be interested if this is possible to do in a reasonably robust way.

Comments