views:

96

answers:

2

Last night I started working on an NHibernate provider. I'm creating a criteria that several records will match, however I only want to return the most recent record (the record with the largest Id). I thought UniqueResult() would do this it cannot be used if a list would be returned otherwise.

I could theoretically select the full list and then return the desired record, but I believe there is a better way.

+1  A: 

Can you add an Order?

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

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

MyType justone = cr.UniqueResult();
Joel Potter
Yes but I'm still returned a list. I only want to get a single object
splatto
You can use in conjunction with `UniqueResult()`. See my update.
Joel Potter
You are right, I misinterpreted the shorthand. I'll give you the correct answer and leave mine below so those in a similar situation can see the full method body. Thanks!
splatto
+1  A: 

Here is ultimately what was required. It was actually a combination of a couple of things I had earlier tried.

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;
splatto