如何配置功能NHibernate输出查询,以跟踪和调试,而不是控制台?
我使用 MsSqlConfiguration.MsSql2008.ShowSql()
,但它不具有任何参数,我无法找到谷歌什么。
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语句,因为他们正在为$ P $见ppared执行。答案通常是沿着你不能行的东西,或者你不应该。
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());
});
}
这不是那么复杂。从我的角度来看,肯定比试图让这一切XML更容易通过流利的推到NHibernate的 - 因为流利的抽象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.
希望这是有帮助的别人! : - )
Hope this is helpful to somebody else! :-)