我正在进行以下加入,有许多bookingActions记录,但我希望每个预订记录只有一个BookingAction记录。我想要具有最高主键值的BookingAction记录。
我该怎么做?
var bookingLocationsQuery = (
from
booking in session.Query<Booking>()
join
bookingActions in session.Query<BookingAction>() on booking.Id equals bookingActions.bookingId
where
(booking.bookingAdminID == userId)
select new { booking, bookingActions }
);
答案 0 :(得分:2)
一些建议。首先,您应该利用NHibernate的many-to-one
为您进行连接,而不是手动完成。看起来你现在有这样的东西......
public class BookingAction
{
// ... other properties ...
public virtual int bookingId { get; set; }
}
<class name="BookingAction">
<!-- ... other properties ... -->
<property name="bookingId" />
</class>
不要那样做。相反,你应该:
public class BookingAction
{
// ... other properties ...
public virtual Booking Booking { get; set; }
}
<class name="BookingAction">
<!-- ... other properties ... -->
<many-to-one name="Booking" column="bookingId" />
</class>
Booking.bookingAdminID
的类似建议。它应该是many-to-one
到User
,而不仅仅是一个简单的属性。
其次,在进行这些更改后,您应该能够通过以下查询来实现目标:
var subquery = session.Query<BookingAction>()
.Where(a => a.Booking.Admin.Id == userId)
.GroupBy(a => a.Booking.Id)
.Select(g => g.Max(a => a.Id));
var bookingActions = session.Query<BookingAction>()
.Fetch(a => a.Booking)
.Where(a => subquery.Contains(a.Id));
很抱歉将其切换为链式扩展方法语法 - 这对我来说更容易使用。它完全等同于执行中的from ... select
语法。
答案 1 :(得分:0)
尝试使用Max()
方法,示例:
var bookingLocation = session.Query<Booking>()
.Where(booking => booking.bookingAdminID == userId)
.Max(x => booking.bookingAdminID);