0

A user can have many addresses, but I want to retrieve the latest entry for the user.

In sql I would do:

SELECT TOP 1 *
FROM UserAddress
WHERE userID = @userID

How can I create a criteria query with the same logic?

Is there a TOP functionality?

Blankman
  • 259,732
  • 324
  • 769
  • 1,199

3 Answers3

4

Assuming that you have some timestamp column (eg. InsertedAt):

    User user = ...;
    var crit = DetachedCriteria.For<UserAddress>()
        .Add(Restrictions.Eq("User", user))
        .AddOrder(Order.Desc("InsertedAt"))
        .SetMaxResults(1);
dariol
  • 1,959
  • 17
  • 26
1

This post has answers to how to do this, but you shouldn't always depend on TOP for getting the latest entry! (assuming chronological order)

Use a time/index column to get the latest entry based on a timestamp value value.

Community
  • 1
  • 1
Mahesh Velaga
  • 21,633
  • 5
  • 37
  • 59
1

Since the ordering of the contents of a table are subject to movement (reindexing etc), I'd suggest that you have a time stamp of some description to indicate which is the latest. Then get the first ordered by that field.

Preet Sangha
  • 64,563
  • 18
  • 145
  • 216