Using nhibernate, how would I build a query that wants the very last 50 lines

I have a table called orders, and I have a column called Last Update (and an order object with the LastUpdate attribute). I want to build a query using nhibernate to get the last 50 rows, so I don’t go to the database and get everything, and then filter the results in my application.

this is possible in nhibernate. I am trying to use LINQ api

+3
source share
5 answers

Here is the LINQ version of this query.

var orders = session.Query<Order>()
    .OrderByDescending(x => x.LastUpdate)
    .Take(50);

Here is a screenshot of the sample code ...

Code example

Here the screen is shot with the NHibernate Profiler ...

NHibernate profiler example

+4
source

, SetMaxResults (50) .

+4

You can use it SetMaxResults(50), although depending on which 50 lines you want (last? First? Last?), You also probably have to execute a SortBy expression.

+1
source
var orders = session.Query<Linq>()
    .OrderByDescending(x => x.LastUpdate)
    .Take(50);
+1
source

In general, a sentence LastUdatecan be null using Linq2SQL, you can write an extension method for your IQueriable:

public static partial class FooTable
{
    public static IQueryable<FooTable> LastUpdated(this IQueryable<FooTable> queryable, int count)
    {
        return queryable.Where(x => (x.LastUdate != null))
            .OrderByDescending(x => x.LastUdate)
            .Take(count);
    }
}
+1
source

All Articles