Search code examples
nhibernatenhibernate-criteria

NHibernate Criteria left antijoin/ subquery confusion


I'll preface this with the fact that NHibernate is well out of my comfort zone, so this may be much simpler than I'm making it out to be.

I have a users table and an events table mapped to user and event objects.

My event objects reference a singular user object.

I have a property that I persist on my user object for LastActivityTimeStamp.

I have properties on my event object related to EventType and Success.

To determine a list of users that are "online", I need to collect all user objects with a LastActivityTimeStamp greater than a previously calculated cutoff value, whose last activity in the events table was not a successful "Logoff" event type.

How would I write this criteria?


Solution

  • try to tweak this

    var subquery = DetachedCriteria.For<Event>()
        .Add(Restrictions.Eq("Success", true))
        .Add(Restrictions.EqProperty("User.Id", "u.id"))
        .AddOrder(Order.Desc("TimeStamp"))
        .SetProjection(Projections.Property("EventType"))
        .SetMaxResults(1);
    
    session.CreateCriteria<User>("u")
        .Add(Restrictions.Ge("LastActivityTimeStamp", cutoff))
        .Add(Subqueries.Ne(EventType.LogOff, subquery));