您好我在使用多连接和左连接创建复杂的Linq时遇到了一些问题。
我最后列出了4个表,这个用于查看我需要如何发送有关主题的新回复的电子邮件。所以我从用户加入的主题中获取所有帖子。同一个用户可以在每个主题中有超过1个帖子。 之后,我加入UserEmailSetting,这是为了查看用户是否已经打开了收到的电子邮件通知。最后,我需要知道是否已向用户发送了一封电子邮件,通知新回复(如果有大量回复,我不想向我的用户发送垃圾邮件),所以如果回复通知自上次发送以来访问该网站我不想再发送邮件。这是我的尝试,但我想优先考虑! 问题是UserEmailSetting上可能有很多结果,所以当我实际上只返回1或2时,我会得到很多os结果。
这是我的照顾
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做的更有条理的布局,我希望它有所帮助
答案 0 :(得分:2)
不保证这将是高效的。
var users = UserRepository.Get();
var userEmailSettings = UsersEmailSettingRepository.Get();
var emailLogs = EmailLogRepository.Get();
var posts = ForumPostRepository.Get();
var foo =
from user in users
where posts
.Any(post => post.UserId == u.Id && post.TopicId == topicId)
where userEmailSettings
.Any(ues => u.Id equals ues.UserId && ues.ReplyToTopic == true)
where false ==
(
from el in emailLogs
where el.Type == "ReplyToTopic"
&& el.Values == topicId
&& el.UserId == user.Id
&& el.Created > user.LastLogin
select el
).Any()
select user;
签名
Linq Ninja
编辑:刚看到你没有导航属性。