开发者

NHibernate use Criteria for Count(),First()

I have a question about Criteria method, one-to-many relation to the database, 'one' is "account", 'many' is "sites", when I use CreateCriteria() something is not right.

Like this: SessionFactory.OpenSession().CreateCriteria(typeof(Account)).List().Count();

Before it's run, I think the SQL should be SELECT COUNT(*) FROM table, but the SQL is SELECT id, siteurl...FROM table. So what's wrong with this? How can I solve it?

And First() method should be SELECT TOP1 ...FROM table, but it is开发者_运维问答 SELECT ...FROM table

I'm an Nhiberate rookie, Please help me.


This happens because the Count method you are calling at the end executes after the query has run and outside of the database. You are only counting the elements in the list in memory. To achieve what you are looking for you could use a projection:

var count = session
    .CreateCriteria<Account>()
    .SetProjection(
        Projections.Count(Projections.Id())
    )
    .UniqueResult<long>();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜