问题描述
我知道如何在运行时使用 show_sql
配置选项将 SQL 记录到 log4net/NLog/trace 窗口.
I know how to log the SQL to log4net/NLog/trace window at runtime with the show_sql
configuration option.
我正在寻找的是一种提供 Query()
以让 NHibernate 检索生成的 SQL 的方法.
What I'm looking for is a way to give a Query<T>()
to NHibernate retrieve the generated SQL.
我浏览了 Persister 类、驱动程序、不同的拦截器和事件.有很多地方可以看,即使缩小我的搜索范围也会有很大帮助.
I've looked through the Persister class, the Drivers, different Interceptors and Events. There are so many places to look, even narrowing down my search would be of great help.
推荐答案
您可以通过以下方法获取不执行生成的 sql 查询:
You can get the generated sql queries without execution with the following methods:
对于 NHibernate.Linq 查询:
For the NHibernate.Linq queries:
public String GetGeneratedSql(System.Linq.IQueryable queryable, ISession session)
{
var sessionImp = (ISessionImplementor) session;
var nhLinqExpression = new NhLinqExpression(queryable.Expression, sessionImp.Factory);
var translatorFactory = new ASTQueryTranslatorFactory();
var translators = translatorFactory.CreateQueryTranslators(nhLinqExpression, null, false, sessionImp.EnabledFilters, sessionImp.Factory);
return translators[0].SQLString;
}
对于条件查询:
public String GetGeneratedSql(ICriteria criteria)
{
var criteriaImpl = (CriteriaImpl) criteria;
var sessionImpl = (SessionImpl) criteriaImpl.Session;
var factory = (SessionFactoryImpl) sessionImpl.SessionFactory;
var implementors = factory.GetImplementors(criteriaImpl.EntityOrClassName);
var loader = new CriteriaLoader((IOuterJoinLoadable) factory.GetEntityPersister(implementors[0]), factory, criteriaImpl, implementors[0], sessionImpl.EnabledFilters);
return loader.SqlString.ToString();
}
对于 QueryOver 查询:
For QueryOver queries:
public String GetGeneratedSql(IQueryOver queryOver)
{
return GetGeneratedSql(queryOver.UnderlyingCriteria);
}
对于 Hql 查询:
public String GetGeneratedSql(IQuery query, ISession session)
{
var sessionImp = (ISessionImplementor)session;
var translatorFactory = new ASTQueryTranslatorFactory();
var translators = translatorFactory.CreateQueryTranslators(query.QueryString, null, false, sessionImp.EnabledFilters, sessionImp.Factory);
return translators[0].SQLString;
}
这篇关于如何让 NHibernate 只生成 SQL 而不执行它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!