【发布时间】:2014-08-16 17:34:07
【问题描述】:
我必须构建一个查询来获取未收到的用户并提醒新帖子。
我的相关表结构如下:
帖子:postId int 用户:userId int、email varchar PostAlertUsers: postAlertUserId int, postId int, userId int
所有相关字段在表之间都有外键约束。
我在 SQL 中构建了这个查询,但找不到在 Entity Framework 中工作的方法:
SELECT u.email
FROM Users u
INNER JOIN Posts p ON p.userId != u.userId
LEFT JOIN PostAlertUsers pu ON u.userId = pu.userId AND p.postId = pu.postId
WHERE pu.postAlertUserId IS NULL
我编写了以下 EF 查询,但没有得到相同的结果:
from u in context.Users
join pu in context.PostAlertUsers on u.userId equals pu.userId into postAlerts
from pa in postAlerts.DefaultIfEmpty()
join p in context.Posts on pa.postId equals p.postId
where pa.userId != u.userId
select u.email;
如何使用 linq to entity 获得相同的结果。使用点语法(我不知道DbSet.Where(x => ...) 语法的正确术语)会更好。
编辑:
对于Posts 中不是来自同一用户的每个Post,我想获取在PostAlertUsers 上没有记录的所有用户。
编辑 2:
试图澄清一点:
对于每个帖子,我只想提醒用户一次其他用户的新帖子,我的例程将每小时运行一次以检查是否有人要发送消息。
我想获取尚未收到有关帖子警告的所有用户,这样它就不会在 PostAlertUsers 上记录此用户和帖子组合,但会记录来自其他用户的帖子。
示例数据:
Users
------------------------
userid | email
------------------------
1 | email1@test.com
2 | email2@test.com
3 | email3@test.com
------------------------
Posts (posts are created by users)
------------------------
postId | userId
------------------------
1 | 1
2 | 3
3 | 1
------------------------
PostAlertUsers (every time a user is notified about a new post, one record is added here)
------------------------
postId | userId
------------------------
1 | 2
1 | 3
2 | 1
------------------------
生成的查询将输出以下数据:
Result (using postId and userId to identify what user have to be notified for what post)
---------------------------------
postId | userId | email
---------------------------------
2 | 2 | email2@test.com
3 | 2 | email2@test.com
3 | 3 | email3@test.com
---------------------------------
编辑:
感谢 AD.Net,我提出了以下建议:
from u in context.Users
let posts = contexto.Posts.Where(p => p.userId != u.userId)
from p in posts
join pau in context.PostAlertUsers on u.userId equals pau.userId
into alerts
from a in alerts.DefaultIfEmpty()
where a == null || a.postId != p.postId
orderby p.idPost
select new {
p.postId,
u.userId,
u.email
}
【问题讨论】:
标签: asp.net sql-server entity-framework linq-to-entities left-join