Implication of using dynamic Expression<Func<T,X>> in NHibernate

♀尐吖头ヾ 提交于 2020-01-03 02:56:14

问题


Basically in my application, I am using the following code to build my expression depending on the selection on the page.

Expression<Func<T, bool>> expr = PredicateBuilder.True<T>();
expr = expr.And(b => b.Speed >= spec.SpeedRangeFrom && b.Speed <= spec.SpeedRangeTo);
...

It has the tendency to end up with a long expression with multiple "or" and "and" conditions.

Once I have finished building the expression, I passed it on to my repository which looks like the following:

var results = Session.Query<T>().Where(expr).ToList();

The problem with that is it took so long to return me the result. I have also noticed that the longer the expression is, the longer it takes to return me the result set.

I have also used NHibernate profiler to analyse the sql statement generated. Running the sql statement separately on SQL Server Studio, it took only less than 1s.

It seems to me most of the time was spent in building or converting the expression to sql statement.

Is there a way to get around this problem?

I don't have many experience in using NHibernate. If anyone can shed some lights on this, that would be great.

Thank you in advance for taking the time to read this.


回答1:


More than the number of returned rows, it is the total number of rows in your table which is important.

Running the sql statement separately on SQL Server Studio, it took only less than 1s.

Testing this way can be misleading. The second run of the queries benefits from the previously compiled SQL statement, the previoulsy calculated query execution plan, the previously filled-up data buffers. Also, testing by replacing, directly in the sql, all parameters names with their values would lead to a different execution plan.

First thing I would do would be to check for wrong usage of the indexes (missing relevant indexes or obsolete statistics)

This can be done by looking at the estimated query execution plan. As to statistics, have a look at : https://dba.stackexchange.com/q/12004

I guess this should be useful too : Query executed from Nhibernate is slow, but from ADO.NET is fast

See below for testing a SQL-SERVER statement with a somewhat cleaned-up environment.

Run this batch for each query to compare execution time and statistics results (Do not run it on a production environment) :

DBCC FREEPROCCACHE
GO

CHECKPOINT 
GO

DBCC DROPCLEANBUFFERS 
GO

SET STATISTICS IO ON
GO

SET STATISTICS TIME ON
GO

-- your query here
GO

SET STATISTICS TIME OFF
GO

SET STATISTICS IO OFF
GO


来源:https://stackoverflow.com/questions/15516185/implication-of-using-dynamic-expressionfunct-x-in-nhibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!