Linq查询3个表

时间:2014-04-26 14:14:04

标签: linq entity-framework

My Domain模型如下:

User  { Id, FirstName, LastName, TeamId }
Team  { Id, Name, Description }
Topic { Id, Title, UserId }

我的应用程序逻辑表明用户应该能够查看他/她团队中的所有主题。

了解上述内容后,如何编写一个linq查询,该查询将获取与用户在同一团队中的人员所做的所有主题?

我尝试了以下内容,但显然是错误的,我只是看不到linq查询的逻辑:(

var topicList = (from u in context.Users
                join t in context.Topics on u.Id equals t.UserId
                where u.TeamId == id
                select new Tourist.WEB.Models.TopicListViewModel
                {
                    Id = t.Id,
                    Title = t.Title,
                    TopicAuthor = u.FirstName,
                    NoOfReplies = 3
                }).ToList();

1 个答案:

答案 0 :(得分:2)

像这样:

from u in context.Users
join t in context.Team on u.TeamId equals t.Id
join to in context.Topic on u.id equals to.UserId
where u.TeamId == id

完整查询:

var topicList = (from u in context.Users
                 join t in context.Team on u.TeamId equals t.Id
                 join to in context.Topic on u.id equals to.UserId
                 where u.TeamId == id
                select new Tourist.WEB.Models.TopicListViewModel
                {
                    Id = to.Id,
                    Title = to.Title,
                    TopicAuthor = u.FirstName,
                    NoOfReplies = 3
                }).ToList();