简体   繁体   中英

NHibernate Criteria, select by count of property

Sorry for the cryptic title..

Could you help me out, on how do a select, based on the count of a property, using Criteria? I have an object (Pool) with a property (PoolItems), and i want to select all the Pools w. more than 5 PoolItems.

Try this:

DetachedCriteria dCriteria = DetachedCriteria.For<PoolItem>("pItem")
            .SetProjection(Projections.Count("Id"))
            .Add(Restrictions.EqProperty("pItem.PoolID", "pool.Id"));

IList<Post> posts = Session.CreateCriteria<Pool>("pool")
                .Add(Subqueries.Gt(5, dCriteria)).List<Pool>();

Assuming the PoolItem table has a PoolID column as a foreign key of the Pool table. The relationship is a one-to-many. If you do not have the PoolID property mapped in the PoolItem class and you just have the many-to-one object mapping named "Pool" then replace in the detached criteria the "pItem.PoolID" with "pItem.Pool.Id".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM