【问题标题】:How to apply sql join in Linq Entity Framework Core如何在 Linq Entity Framework Core 中应用 sql join
【发布时间】:2020-08-27 14:54:46
【问题描述】:

我有三张桌子:

  • 用户(ID、用户名)
  • 成员身份(Id、UserId、GroupId)
  • 组(ID、组名)

如何使用 LINQ 应用此查询:

select Username, GroupName
from (([Membership]
inner join [User]  on [Membership].UserId = [User].Id)
inner join [Group] on [Membership].GroupId = [Group].Id)
where [Group].Id = 1

【问题讨论】:

标签: c# sql linq entity-framework-core asp.net-core-mvc


【解决方案1】:
var member = Context.membership 
                    .Include(i => i.user)
                    .Include(i => i.group)
                    .Where(i => i.Id == id)

【讨论】:

  • public class user { [Foreign Key("membership")] public int members Id { get;放; } 公共虚拟会员资格 { 获取;放; } } public class group { [ForeignKey("group")] public int group Id { get;放; } 公共虚拟组组 { 获取;放; } }
  • 不要将代码放在后续评论中,而是编辑您的答案以将其包含为格式化代码。当你在做的时候,我建议你在这里做一个额外的解释来帮助 OP——以及未来的读者!——理解为什么这是一个好方法。提前谢谢!
【解决方案2】:

你可以这样使用:

from membership in MembershipRepository.GetAll()
join user in UserRepository.GetAll() on membership.UserId equals user.id
join group in GroupRepository.GetAll() on membership.GroupId equals group.id 
where group.id == 1
select new {user.Username, group.GroupName};

但是,这不适用于左连接或右连接。他们的语法略有不同

【讨论】:

  • 谢谢,有没有其他方法可以在 EF 内核中使用 Include 和 ThenInclude?​​span>
猜你喜欢
  • 1970-01-01
  • 2018-09-08
  • 2022-08-20
  • 2020-07-09
  • 1970-01-01
  • 1970-01-01
  • 2020-05-17
  • 2020-09-16
  • 2016-06-30
相关资源
最近更新 更多