c# – 如何在子集合的Nhibernate中执行QueryOver
作者:互联网
您好我有一个名为Notifications的类,它是User的子类.
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string UserName { get; set; }
public ICollection<UserNotification> UserNotifications { get; set; }
}
public class Notification
{
public int Id { get; set; }
public ICollection<UserNotification> UserNotifications { get; set; }
public string Title { get; set; }
public string Message { get; set; }
public bool IsRead { get; set; }
public DateTime CreatedDate { get; set; }
}
public class UserNotification
{
public User User { get; set; }
public Notification Notification { get; set; }
}
现在我想获取User By ID,它将为当前用户提供所有通知.
var user = NhSession.Get<User>(userId);
但我不想收到所有通知.我只想让用户获得未读通知,并且只想获得用户的前5(最新)通知.
我尝试通过joinQueryOver实现这一点,但我无法做到这一点.任何人都可以建议让这个工作.
解决方法:
基于最新的更新和新的Entity(ies)结构,我们现在可以从Pairing对象中获利,并快速选择具有未读Notificaitons的用户
查找尚未阅读通知的用户
var session = NHSession.GetCurrent();
Notification notification = null;
UserNotification pair = null;
User user = null;
var subquery = QueryOver.Of<UserNotification>(() => pair)
// this will give us access to notification
// see we can filter only these which are NOT read
.JoinQueryOver(() => pair.Notification, () => notification)
// here is the filter
.Where(() => !notification.IsRead)
// now the trick to take only related to our user
.Where(() => pair.User.Id == user.Id)
// and get the user Id
.Select(x => pair.User.Id);
var listOfUsers = session.QueryOver<User>(() => user)
.WithSubquery
.WhereProperty(() => user.Id)
.In(subquery)
// paging
.Take(10)
.Skip(10)
.List<User>();
每个userId查找5个未读通知
var userId = 1;
var subqueryByUser = QueryOver.Of<UserNotification>(() => pair)
// now we do not need any kind of a join
// just have to filter these pairs related to user
.Where(() => pair.User.Id == userId)
// and get the notification Id
.Select(x => pair.Notification.Id);
var notificationsPerUser = session.QueryOver<Notification>(() => notification)
.WithSubquery
.WhereProperty(() => notification.Id)
.In(subqueryByUser)
.Where(() => !notification.IsRead)
// if needed we can order
// .OrderBy(...
.Take(5)
.List<Notification>()
标签:c,nhibernate,queryover 来源: https://codeday.me/bug/20190609/1206521.html