简体   繁体   English

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

[英]How to configure Fluent NHibernate to output queries to Trace or Debug instead of Console?

How to configure Fluent NHibernate to output queries to Trace or Debug instead of Console? 如何配置Fluent NHibernate将查询输出到Trace或Debug而不是Console? I'm using MsSqlConfiguration.MsSql2008.ShowSql() but it has no parameters and I can't find anything on Google. 我正在使用MsSqlConfiguration.MsSql2008.ShowSql()但它没有参数,我在谷歌上找不到任何东西。

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. 我可以从论坛和博客文章中看到,在我之前的很多其他人都在寻找一种方法来获取SQL语句,因为他们正在准备执行。 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. 当然,您不必在此处使用Trace.WriteLine() ,您可以将其写入日志文件或其他任何需要的文件。

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. 从我的角度来看,肯定比通过Fluent将所有这些XML推送到NHibernate更容易 - 因为Fluent将XML文件抽象化了。

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 - eg MyAppInterceptor, so as not to imply a specific purpose, because you may want to add other features to it later. 在这方面,您可能希望给它一个更广泛的名称 - 例如MyAppInterceptor,以免暗示特定目的,因为您可能希望稍后添加其他功能。

Hope this is helpful to somebody else! 希望这对其他人有帮助! :-) :-)

You probably want to use log4net, not ShowSql. 您可能想使用log4net,而不是ShowSql。 Here is some configuration to send queries to Debug: 以下是一些向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: 然后在打开NHibernate会话之前从代码中调用它:

log4net.Config.XmlConfigurator.Configure();

When you add a reference to the log4net DLL, make sure to set its "Copy Local" property to "true". 添加对log4net DLL的引用时,请确保将其“Copy Local”属性设置为“true”。

This isn't specific to FluentNHibernate, it works the same in any variant of NHibernate. 这不是特定于FluentNHibernate,它在NHibernate的任何变体中都是一样的。

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). 我没有尝试使用SQL Server,但是使用SQLite,以下代码将在“ 输出”窗口中显示生成的SQL(调试菜单 - > Windows - >输出,在VS2008中)。

The "Show output from:" combo box in the Output window should be set to "Debug" - VS2008 did that for me automatically. “输出”窗口中的“显示输出:”组合框应设置为“调试” - VS2008会自动为我执行此操作。

            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. 一句警告 - 打开此功能可以大大减慢执行速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM