user1000528
user1000528

Reputation: 23

Implement first last in Nhibernate

I am trying to implement First and last in my navigation using nhibernate.On click of first i am able to find first row using given function

public IList<T> GetFirstItem<T>()
    {
        using (ISession session = MvcApplication.SessionFactory.GetCurrentSession())
        {
            using (session.BeginTransaction())
            {
                return session.CreateCriteria(typeof(T)).SetFirstResult(0)
                .SetMaxResults(1)
               .List<T>();
            }
        }
    }

But i am not able to implement last button.I dont want to use two queries. Is it possible to find last item in a single Nhibernate query?

Upvotes: 0

Views: 266

Answers (2)

Torbj&#246;rn Kalin
Torbj&#246;rn Kalin

Reputation: 1986

Your implementation of GetFirstItem() does not guarantee to return the first item since a select query may return items in whatever order it pleases. So you get the first result in a random list.

To get your method to work properly you need to add a .AddOrder(Order.Asc("<some property>")) call to your criteria where <some property> could be a database id or a creation timestamp.

To get the last item, add a .AddOrder(Order.Desc("<some property>")) call instead.

(By the way, why do you return a list from a method that should get you one item only?)

Upvotes: 1

Low Flying Pelican
Low Flying Pelican

Reputation: 6054

I think you probably want to use some kind of sorting to determine first and last items, so you could use sort ASC to get the first and use DESC to get the last with adding sorting to your current code.

Upvotes: 1

Related Questions