c# - 哪一款性能更好?

标签 c# nhibernate orm hql icriteria

我使用 NHibernate 用两种方法编写相同的查询:

1- 通过使用 HQL 如下所示

public long RetrieveHQLCount<T>(string propertyName, object propertyValue)
{
    using (ISession session = m_SessionFactory.OpenSession())
    {
        long r = Convert.ToInt64(session.CreateQuery("select count(o) from " + typeof(T).Name + " as o" + " where o." + propertyName + " like '" + propertyValue + "%'").UniqueResult());
        return r;
    }
}

2- 通过使用 ICriteriaSetProjections 如下

public long RetrieveCount<T>(string propertyName, object propertyValue)
{
    using (ISession session = m_SessionFactory.OpenSession())
    {
        // Create a criteria object with the specified criteria
        ICriteria criteria = session.CreateCriteria(typeof(T));
        criteria.Add(Expression.InsensitiveLike(propertyName, propertyValue))
            .SetProjection(Projections.Count(propertyName));

        long count = Convert.ToInt64(criteria.UniqueResult());

        // Set return value
        return count;
    }
}

现在我的问题是哪一个性能更好?为什么?

最佳答案

我认为获得更好指标的最佳方法是如此处所述。去下载 nhProf 并对其进行分析。

http://nhprof.com/

如果您想要更多详细信息,请获取生成的 SQL,然后通过 SQL Server Profiler 运行它,以更好地了解它正在做什么。

但老实说,如果数据库中有任何数量的数据,那么执行 LIKE 查询将会给你带来可怕的结果。

我强烈建议您在 SQL Server 中设置全文索引,然后使用它:

http://nhforge.org/blogs/nhibernate/archive/2009/03/13/registering-freetext-or-contains-functions-into-a-nhibernate-dialect.aspx

在nHibernate中注册自由文本和包含函数。

与 ICriteria 查询集成的另一个很好的示例如下:

http://xlib.wordpress.com/2009/12/04/integrating-freetext-search-in-nhibernate-detached-criteria/

或者,您也可以使用 Lucene.NET 进行全文索引。

关于c# - 哪一款性能更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2780432/

相关文章:

c# - 从代码隐藏调用命令

c# - 按子列表属性排序父对象列表

mysql - 我如何编写一个需要可操作的 mySQL 数据库的测试模块?

c# - 具有行为和 ORM 的丰富域模型

sql-server - 在 NHibernate 中使用 Guid Version 列

python - 为什么 select_for_update 在并发插入中起作用?

串行端口中的 C# DtrEnable 和 RtsEnable

c# - MVC 模型绑定(bind) - 抽象集合属性

c# - MD5 散列的奇怪行为

c# - NHibernate 映射 : Save hierarchy to single table without discriminator