¿Cómo puedo ver el SQL generado por nHibernate?


¿Cómo puedo ver el SQL generado por NHibernate? versión 1.2

 36
Author: Larry Foulkrod, 2008-09-24

8 answers

Puedes poner algo como esto en tu app.config / web.archivo de configuración :

En el nodo configSections:

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>

En el nodo de configuración:

<log4net>
  <appender name="NHibernateFileLog" type="log4net.Appender.FileAppender">
    <file value="logs/nhibernate.txt" />
    <appendToFile value="false" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n"  />
    </layout>
  </appender>
  <logger name="NHibernate.SQL" additivity="false">
    <level value="DEBUG"/>
    <appender-ref ref="NHibernateFileLog"/>
  </logger>
</log4net>

Y no olvides llamar

log4net.Config.XmlConfigurator.Configure();

Al inicio de su aplicación, o para poner

[assembly: log4net.Config.XmlConfigurator(Watch=true)]

En el assemblyinfo.cs

En la configuración, establezca la propiedad "show_sql" en true.

 40
Author: mathieu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-31 08:59:18

En la configuración, establezca la propiedad "show_sql" en true. Esto hará que el SQL se genere en los archivos de registro de NHibernate cortesía de log4net.

 17
Author: Ian Nelson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-24 19:02:03

Estoy un poco tarde, lo sé, pero esto hace el truco y es independiente de la herramienta/db/framework. En lugar de esas opciones válidas, utilizo Interceptores NH.

Al principio, implementar una clase que extiende NHibernate.EmptyInterceptor e implementa NHibernate.IInterceptor :

using NHibernate;

namespace WebApplication2.Infrastructure
{
    public class SQLDebugOutput : EmptyInterceptor, IInterceptor
    {
        public override NHibernate.SqlCommand.SqlString
           OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)
        {
            System.Diagnostics.Debug.WriteLine("NH: " + sql);

            return base.OnPrepareStatement(sql);
        }
    }
}

Luego, simplemente pase una instancia cuando abra su sesión. Asegúrate de hacerlo solo cuando estés en DEBUG:

public static void OpenSession() {

#if DEBUG
    HttpContext.Current.Items[SessionKey] = _sessionFactory.OpenSession(new SQLDebugOutput());

#else
    HttpContext.Current.Items[SessionKey] = _sessionFactory.OpenSession();

#endif
}

Y eso es todo.

A partir de ahora, sus comandos sql como estos...

 var totalPostsCount = Database.Session.Query<Post>().Count();

 var currentPostPage = Database.Session.Query<Post>()
        .OrderByDescending(c => c.CreatedAt)
        .Skip((page - 1) * PostsPerPage)
        .Take(PostsPerPage)
        .ToList();

.. se muestran directamente en la ventana de salida:

NH: select cast (count(*) as INT) as col_0_0_ from posts post0_

NH: seleccionar post0_.Id como Id3_, post0_.user_id como user2_3_, post0_.Título Title3_, post0_.Slug as Slug3_, post0_.Contenido como Content3_, post0_.created_at as created6_3_, post0_.updated_at como updated7_3_, post0_.deleted_at as deleted8_3_ from posts post0_ ordenar por post0_.created_at desc limit ? offset ?

 7
Author: Alexander,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-20 02:54:28

Utilice sql server profiler.

EDITAR (1 año después): Como @Toran Billups afirma a continuación, el NHibernate profiler Ayende escribió es muy, muy genial.

 6
Author: Iain Holder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-24 10:28:48

También puede probar NHibernate Profiler (prueba de 30 días si nada más). Esta herramienta es la mejor alrededor de MI Humilde opinión.

Esto no solo mostrará el SQL generado sino también advertencias/sugerencias/etc

 5
Author: Toran Billups,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-12 15:03:45

Hay una buena referencia para el registro de NHibernate en: Cómo configurar Log4Net para su uso con NHibernate. Incluye información sobre el registro de todas las sentencias SQL generadas por NHibernate.

 3
Author: Sean Carpenter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-24 19:10:30

Nhibernate Profiler es una opción, si tienes que hacer algo serio.

 1
Author: Dan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-12 15:01:55

Si está utilizando SQL Server (no Express), puede probar SQL Server Profiler.

 1
Author: David Kennedy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-31 18:01:17