NHibernate Linq Query with Projection and Count error

一笑奈何 提交于 2019-12-05 16:14:01

The point is, that we should NOT call Count() over projection. So this will work

var query = repositoy.Query<MyClass>;
var list = query.Select(domain => new MyDto()
{ 
    Id = domain.Id,
    StringComma = string.Join(",", domain.MyList.Select(y => y.Name))
});

var count = query.Count();

When we use ICriteria query, the proper syntax would be

var criteria = ... // criteria, with WHERE, SELECT, ORDER BY...

// HERE cleaned up, just to contain WHERE clause
var totalCountCriteria = CriteriaTransformer.TransformToRowCount(criteria);

So, for Count - use the most simple query, i.e. containing the same JOINs and WHERE part

If you really don't need the results, but only the count, then you shouldn't even bother writing the .Select() clause. Radim's answer as posted is a good way to both get the results and the count, but if your database supports it, use future queries to execute both in the same roundtrip to the database:

var query = repository.Query<MyClass>;
var list = query.Select(domain => new MyDto()
{ 
    Id = domain.Id,
    StringComma = string.Join(",", domain.MyList.Select(y => y.Name))
}).ToFuture();

var countFuture = query.Count().ToFutureValue();

int actualCount = countFuture.Value; //queries are actually executed here

Note that there in NH prior to 3.3.3, this would still execute two round-trips (see https://nhibernate.jira.com/browse/NH-3184), but it would work, and if you ever upgrade NH, you get a (minor) performance boost.

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