你好,我在创建一个复杂的 Linq 查询时遇到一些问题,需要进行多个连接和左连接操作。
我有四个表,如下所示。这是用于查看如何发送关于主题的新回复的电子邮件。因此,我获取加入了用户的所有帖子。同一用户在每个主题中可以有多个帖子。之后,我加入 UserEmailSetting,这是为了查看用户是否选择不接收电子邮件通知。最后,我需要知道是否已向用户发送了有关新回复的电子邮件(如果有大量回复,我不想垃圾邮件我的用户),因此,如果自上次访问网站以来已发送回复通知,则不想再发送另一封邮件。以下是我尝试过的代码,它能正常工作,但我想进行优化!
问题在于 UserEmailSetting 可能会有很多结果,因此当我实际上只返回 1 或 2 个结果时,我会得到很多结果。
以下是我的尝试:
var select = (from p in ForumPostRepository.Get()
join u in UserRepository.Get() on p.UserId equals u.Id
join ues in UsersEmailSettingRepository.Get() on u.Id equals ues.UserId
join els in
(from _el in EmailLogRepository.Get()
where _el.Type == "ReplyToTopic" &&
_el.Values == topicId
orderby _el.Id descending
select _el) on u.Id equals els.UserId
into emailLogs
from el in emailLogs.DefaultIfEmpty()
where p.TopicId == forumTopic.Id &&
ues.ReplyToTopic //&& // We only want people who need notifications
//!u.Online // We only want people who are not online
orderby p.Id descending, el.Id descending
select new
{
User = u,
EmailLog = el
});
var result = select.DistinctBy(x => x.User.Id).ToList();
这里是数据库类。
public class ForumPost
{
public int? TopicId { get; set; }
public int UserId { get; set; }
...
}
public class User
{
public int Id { get; set; }
public bool Online { get; set; }
public DateTime LastLogin { get; set; }
...
}
public class UsersEmailSetting
{
public int UserId { get; set; }
public bool ReplyToTopic { get; set; }
}
public class EmailLog
{
public int Id { get; set; }
public int UserId { get; set; }
public string Type { get; set; }
public string Values { get; set; }
public DateTime Created { get; set; }
}
更新:我希望更结构化地描述我想让Linq做什么,希望这能有所帮助。
- 从ForumPostRepository获取所有主题ID为13的文章。
- 在ForumPostRepository.UserId = UserRepository.Id的条件下与UserRepository进行连接。
- 现在只想要不同的用户。
- 在UserRepository.Id = UsersEmailSettingRepository.UserId的条件下与UsersEmailSettingRepository进行连接。
- 在UserRepository.Id = EmailLogRepository.UserId并且EmailLogRepository.Type =“ReplyToTopic”以及EmailLogRepository.Values =“topicId”的条件下进行左连接。
- -> 现在可以得到0至*个结果,但我只想要最新的一个!