其中子句在 NHibernate
本文关键字:NHibernate 子句 | 更新日期: 2023-09-27 18:36:24
如何在NHibernate中表达这一点?
DECLARE @EntityId INT = 800;
SELECT *
FROM UserAlert
WHERE UserAlertId =
(
SELECT MAX(UserAlertId)
FROM UserAlert
WHERE EntityId = @EntityId
)
这就是我要做的。
var senderUA = session.CreateCriteria<UserAlert>()
.Add(Restrictions.Eq("EntityId", id))
.SetProjection( Projections.Max("Id") )
. UniqueResult();
而且我不断收到一个错误,可以将对象转换为UserAlert类型,即它甚至没有编译。
感谢您的帮助
按 UserAlertId 降序排序并选择前 1 名会更简单。
var senderUA = session.CreateCriteria<UserAlert>()
.Add(Restrictions.Eq("EntityId", id))
.AddOrder(Order.Desc("UserAlertId"))
.SetMaxResults(1)
.UniqueResult();
此外,您还可以
var senderUA = session
.Query<UserAlert>()
.Where(x=>x.EntityId==id &&
x.UserAlertId==session.Query<UserAlert>()
.Where(x=>x.EntiryId==id).Max(x=>x.UserAlertId)
).FirstOrDefault();
这是使用 QueryOver
的解决方案。
var maxUserAlertId = QueryOver.Of<UserAlert>
.Where(ua => ua.EntityId == id)
.Select(
Projections.Max(
Projections.Property<UserAlert>
(u => u.UserAlertId)
)
);
var maxUserQuery = session
.QueryOver<UserAlert>()
.WithSubquery
.WhereProperty(u => u.EntityId)
.Eq(maxUserAlertId);
// Dealing with the situation that the maximum value is shared
// by more than one row. If you're certain that it can only
// be one, call SingleOrDefault instead of List
IList<UserAlert> results = maxUserQuery.List();