你好,我在创建一个复杂的
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; }
}
Updata:我希望linq做的更有条理的布局,我希望它有所帮助
>从ForumPostRepository获取所有帖子,其中topicId为13
>在ForumPostRepository.UserId = UserRepository.Id上加入UserRepository
>现在我只想要不受欢迎的用户
>在UserRepository.Id =上加入UsersEmailSettingRepository
UsersEmailSettingRepository.UserId
>在UserRepository.Id =上与EmailLogRepository进行左连接
EmailLogRepository.UserId和EmailLogRepository.Type =
“ReplyToTopic”和EmailLogRepository.Values =“topicId”
> – >现在这个请求可以有从0到*的结果,我只想要最新的!
最佳答案 不保证这将是高效的.
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
编辑:刚看到你没有导航属性.