如何配置 Fluent NHibernate 将查询输出到 Trace 或 Debug 而不是 Console? [英] How to configure Fluent NHibernate to output queries to Trace or Debug instead of Console?

查看:12
本文介绍了如何配置 Fluent NHibernate 将查询输出到 Trace 或 Debug 而不是 Console?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何配置 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.

推荐答案

我可以从论坛和博客文章中看到,在我之前的很多其他人都在寻找一种方法来获取准备执行的 SQL 语句.答案通常类似于你不能"或你不应该".

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.

编写一个拦截器:

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(),您可以将其写入日志文件或其他任何您需要的文件.

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());
                                   });
}

没那么复杂.从我的角度来看,这肯定比试图通过 Fluent 将所有这些 XML 推送到 NHibernate 更容易——因为 Fluent 将 XML 文件抽象化了.

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.

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

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.

这篇关于如何配置 Fluent NHibernate 将查询输出到 Trace 或 Debug 而不是 Console?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆