开发者

NHibernate select most recent record that meets criteria

开发者 https://www.devze.com 2022-12-18 02:47 出处:网络
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

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 开发者_JS百科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.


Can you add an Order?

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

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

MyType justone = cr.UniqueResult();


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

精彩评论

暂无评论...
验证码 换一张
取 消