开发者

nhibernate, Retrieve the latest row in a table

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?


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


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜