Nhibernate为查询添加选项

时间:2012-12-04 18:19:06

标签: nhibernate

我最近遇到了Nhibernate生成SQL的性能问题,如

中所述

Nhibernate generate plain sql query instead of execution statement

我还找到了一个描述类似经历的链接,来自唯一的杰夫阿特伍德

http://legeronline.blogspot.ca/2009/03/evils-of-slow-paramaterized-query-plans.html

有没有人知道是否还有为Nhibernate添加“Optimize Uknown”选项?

2 个答案:

答案 0 :(得分:2)

这个例子有点冗长:

public class OptionInterceptor: EmptyInterceptor
{
    public override SqlString OnPrepareStatement(SqlString sql)
    {
        var parameters = sql.GetParameters();
        var paramCount = parameters.Count();

        if (paramCount == 0)
            return sql;

        string optionString = " OPTION (OPTIMIZE FOR (";

        for (var i = 0; i < paramCount; i++)
        {
            var comma = i > 0 ? "," : string.Empty;
            optionString = optionString + comma + "@p" + i + " UNKNOWN";
        }

        optionString = optionString + "))";

        var builder = new SqlStringBuilder(sql);

        builder.Add(optionString);

        return builder.ToSqlString();
    }
}

然后在你的sessionfactory / initializer中:

configuration.ExposeConfiguration(x =>
    {
        x.SetInterceptor(new OptionInterceptor());
    });

答案 1 :(得分:0)

  • 您可以考虑扩展MsSqlDialect或
  • 实现IConnectionProvider以注入您自己的命令包装器,该命令包装器在调用ExecuteReader()时添加提示