我如何在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类型的错误,即它甚至没有编译。
感谢您的帮助
答案 0 :(得分:3)
按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();
答案 1 :(得分:0)
以下是使用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();