gpt4 book ai didi

c# - 如何在 Nhibernate 中对子集合执行 QueryOver

转载 作者:太空狗 更新时间:2023-10-30 01:03:37 24 4
gpt4 key购买 nike

你好,我有一个名为 Notifications 的类,它是用户的子类。

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

现在我想通过 ID 获取用户,这将为当前用户带来所有通知。

var user = NhSession.Get<User>(userId);

但我不想收到所有通知。我只想让用户收到未读通知,并且只想为用户获取 前 5 个(最新)通知

我试图通过 joinQueryOver 来实现,但我无法做到。任何人都可以建议让这个工作。

最佳答案

基于最新的更新和新的 Entity(ies) 结构,我们现在可以从 Pairing 对象中获益,并像这样快速选择具有未读通知的用户

查找未阅读通知的用户

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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27478172/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com