如何配置 Fluent NHibernate 将查询输出到 Trace 或 Debug 而不是 Console?

发布于 2024-08-19 19:23:16 字数 148 浏览 4 评论 0原文

如何配置 Fluent NHibernate 将查询输出到 Trace 或 Debug 而不是 Console? 我正在使用 MsSqlConfiguration.MsSql2008.ShowSql() 但它没有参数,我在 Google 上找不到任何内容。

How to configure Fluent NHibernate to output queries to Trace or Debug instead of Console?
I'm using MsSqlConfiguration.MsSql2008.ShowSql() but it has no parameters and I can't find anything on Google.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

ㄖ落Θ余辉 2024-08-26 19:23:16

我可以从各地的论坛和博客文章中看到,在我之前的许多人都在寻找一种方法来获取正在准备执行的 SQL 语句。答案通常是“你不能”或“你不应该”。

不管我该不该,这就是我想要的。

经过几个小时的搜索、调查和失败的尝试,我终于想出了这个。

编写拦截器:

using NHibernate;
using System.Diagnostics;

public class SqlStatementInterceptor : EmptyInterceptor
{
    public override NHibernate.SqlCommand.SqlString OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)
    {
        Trace.WriteLine(sql.ToString());
        return sql;
    }
}

当然,您不必在此处 Trace.WriteLine(),您可以将其写入日志文件或您需要的任何其他文件。

在你的连接管理器中,像这样连接你的拦截器:

protected virtual void Configure(FluentConfiguration config)
{
    config.ExposeConfiguration(x =>
                                   {
                                       x.SetInterceptor(new SqlStatementInterceptor());
                                   });
}

它并不那么复杂。从我的角度来看,这肯定比尝试将所有这些 XML 通过 Fluent 推送到 NHibernate 更容易 - 因为 Fluent 抽象了 XML 文件。

请记住,您只能拥有一个拦截器 - 因此您可能需要将此功能与现有拦截器集成(如果您已经有一个拦截器)。在这一点上,您可能想给它一个更广泛的名称 - 例如 MyAppInterceptor,以免暗示特定目的,因为您稍后可能想向其添加其他功能。

I can see from forum and blog posts everywhere that lots of others before me have looked for a way to get the SQL statements as they're being prepared for execution. The answer typically is something along the lines of "you can't", or "you shouldn't".

Whether I should or not, that's what I wanted.

After hours of searching, investigation and failed attempts, and finally I came up with this.

Write up an interceptor:

using NHibernate;
using System.Diagnostics;

public class SqlStatementInterceptor : EmptyInterceptor
{
    public override NHibernate.SqlCommand.SqlString OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)
    {
        Trace.WriteLine(sql.ToString());
        return sql;
    }
}

Of course, you don't have to Trace.WriteLine() here, you could write it to a log file, or whatever else you need.

In your connection manager, hook up your Interceptor like so:

protected virtual void Configure(FluentConfiguration config)
{
    config.ExposeConfiguration(x =>
                                   {
                                       x.SetInterceptor(new SqlStatementInterceptor());
                                   });
}

It's not that complicated. From my perspective, certainly easier than trying to get all this XML pushed through Fluent to NHibernate - since Fluent abstracts the XML file away.

Keep in mind, you can only have a single Interceptor - so you may need to integrate this feature with your existing Interceptor, if you already have one. On that note, you might want to give it a broader name - e.g. MyAppInterceptor, so as not to imply a specific purpose, because you may want to add other features to it later.

待天淡蓝洁白时 2024-08-26 19:23:16

您可能想使用 log4net,而不是 ShowSql。以下是发送查询到 Debug 的一些配置:

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

  <log4net debug="false">
    <appender name="WindowsDebugOutput" type="log4net.Appender.DebugAppender,
         log4net">
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern"
              value="%d{ABSOLUTE} %-5p %c{1}:%L - %m%n" />
      </layout>
    </appender>

    <logger name="NHibernate.SQL" additivity="false">
      <level value="DEBUG" />
      <appender-ref ref="WindowsDebugOutput" />
    </logger>
  </log4net>

然后在打开 NHibernate 会话之前从代码中调用此配置:

log4net.Config.XmlConfigurator.Configure();

添加对 log4net DLL 的引用时,请确保将其“Copy Local”属性设置为“true”。

这并不是 FluentNHibernate 特有的,它在 NHibernate 的任何变体中都一样工作。

You probably want to use log4net, not ShowSql. Here is some configuration to send queries to Debug:

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

  <log4net debug="false">
    <appender name="WindowsDebugOutput" type="log4net.Appender.DebugAppender,
         log4net">
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern"
              value="%d{ABSOLUTE} %-5p %c{1}:%L - %m%n" />
      </layout>
    </appender>

    <logger name="NHibernate.SQL" additivity="false">
      <level value="DEBUG" />
      <appender-ref ref="WindowsDebugOutput" />
    </logger>
  </log4net>

And then call this from your code before opening an NHibernate session:

log4net.Config.XmlConfigurator.Configure();

When you add a reference to the log4net DLL, make sure to set its "Copy Local" property to "true".

This isn't specific to FluentNHibernate, it works the same in any variant of NHibernate.

一袭水袖舞倾城 2024-08-26 19:23:16

我还没有在 SQL Server 上尝试过这个,但是在 SQLite 上,下面的代码将在 Output 窗口中显示生成的 SQL(调试菜单 -> Windows -> 输出,在 VS2008 中)。

输出窗口中的“显示输出:”组合框应设置为“调试” - VS2008 自动为我完成了这一点。

            sessionFactory = Fluently.Configure()
                .Database(SQLiteConfiguration.Standard
                            .UsingFile(DbFile)
                            // Display generated SQL in Output window
                            .ShowSql()
                          )
                .Mappings(m => m.AutoMappings.Add( GetAutoPersistenceModel() ))
                .BuildSessionFactory()
                ;

警告一句 - 打开此功能会大大减慢执行速度。

I have not tried this with SQL Server, but with SQLite, the following code will show generated SQL in the Output window (Debug menu -> Windows -> Output, in VS2008).

The "Show output from:" combo box in the Output window should be set to "Debug" - VS2008 did that for me automatically.

            sessionFactory = Fluently.Configure()
                .Database(SQLiteConfiguration.Standard
                            .UsingFile(DbFile)
                            // Display generated SQL in Output window
                            .ShowSql()
                          )
                .Mappings(m => m.AutoMappings.Add( GetAutoPersistenceModel() ))
                .BuildSessionFactory()
                ;

A word of warning - turning this on can slow down execution considerably.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文