NHibernate Selection criteria for all objects with empty child collections

It's hard for me to write criteria to select all entities with empty child collections or empty grand-child collections. I can do this as a separate criterion, but I have problems with combining into one criterion.

Class structure:

public class Component
    {
        public IList<Version> Versions { get; set; }
    }

    public class Version
    {
        public IList<SubscribeEvent> SubscribedEvents { get; set; }
        public IList<PublishEvent> PublishedEvent { get; set; }
    }

This does not work:

return session
                .CreateCriteria<Component>("c")
                .CreateCriteria("Versions", "v")
                .Add(Restrictions.Or(Restrictions.IsEmpty("c.Versions"), Restrictions.And(Restrictions.IsEmpty("v.PublishedEvents"),
                                                                                        Restrictions.IsEmpty("v.SubscribedEvents"))))
                .SetCacheable(true);
+3
source share
1 answer

I managed to work out a solution, not sure if this is the best (I have to buy an NH profiler)

return session
            .CreateCriteria<Component>("c")
            .CreateAlias("Versions", "v", JoinType.LeftOuterJoin)
            .Add(Restrictions.Or(Restrictions.IsEmpty("c.Versions"),
                                 Restrictions.And(Restrictions.IsEmpty("v.SubscribedEvents"),
                                                  Restrictions.IsEmpty("v.PublishedEvents"))))
            .SetCacheable(true);
+3
source

Source: https://habr.com/ru/post/1744375/


All Articles