Getting the SQL from a LINQ Query in NHibernate
In case you ever want to have a look at the generated SQL before it is actually executed, you can use this extension method:
1: public static String ToSql(this IQueryable queryable)
2: {
3: var sessionProperty = typeof(DefaultQueryProvider).GetProperty("Session", BindingFlags.NonPublic | BindingFlags.Instance);
4: var session = sessionProperty.GetValue(queryable.Provider, null) as ISession;
5: var sessionImpl = session.GetSessionImplementation();
6: var factory = sessionImpl.Factory;
7: var nhLinqExpression = new NhLinqExpression(queryable.Expression, factory);
8: var translatorFactory = new ASTQueryTranslatorFactory();
9: var translator = translatorFactory.CreateQueryTranslators(nhLinqExpression, null, false, sessionImpl.EnabledFilters, factory).First();
10: //in case you want the parameters as well
11: //var parameters = nhLinqExpression.ParameterValuesByName.ToDictionary(x => x.Key, x => x.Value.Item1);
12:
13: return translator.SQLString;
14: }
Just call it on an IQueryable or IQueryable<T> instance, such as the one you got from ISession.Query<T>:
1: var query = session.Query<Product>().Where(p => p.Price > 100);
2: var sql = query.ToSql();
Parameters such as 100 will be located in the nhLinqExpression.ParameterValuesByName collection.