NHibernate selects the most recent entry that matches the criteria

Last night I started working with an NHibernate provider. I create matching criteria for several records, however I only want to return the most recent record (the record with the largest identifier). I thought UniqueResult () would do this; it cannot be used unless the list is returned otherwise.

I could theoretically select the complete list and then return the desired entry, but I believe that there is a better way.

+3
source share
2 answers

Can you add an order?

ICriteria cr = Session.CreateCriteria<MyType>();

cr.AddOrder(Order.Desc("Id"));

MyType justone = cr.UniqueResult();
+4
source

, . , .

MyObject mo = (MyObject)_session.CreateCriteria(typeof(MyObject))
                .Add(Restrictions.Eq("Property", value))
                .AddOrder(Order.Desc("Id"))
                .SetMaxResults(1).UniqueResult();
            Log.Info(this, string.Format("Retrieving latest MyObject {0}.", mo.Name));
            return mo;
0

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


All Articles