.net ef 3中多对多关系的复杂查询
在我的项目中,每个用户都有一个或多个组,每个组都有一个或多个角色 在用户登录之后,我想使用EntityFramework3获取该用户的角色。 这些就是我的模型 用户模型.net ef 3中多对多关系的复杂查询,.net,asp.net-mvc,entity-framework,asp.net-core,.net-core,.net,Asp.net Mvc,Entity Framework,Asp.net Core,.net Core,在我的项目中,每个用户都有一个或多个组,每个组都有一个或多个角色 在用户登录之后,我想使用EntityFramework3获取该用户的角色。 这些就是我的模型 用户模型 public class User { public User() { userGroups = new List<UserGroup>(); } public int Id { get; set; }
public class User
{
public User()
{
userGroups = new List<UserGroup>();
}
public int Id { get; set; }
[Display(Name = "UserName")]
[Required]
public string Username{get;set;}
public ICollection<UserGroup> userGroups{get;set;}
}
榜样
public class Role
{
public int Id{get;set;}
public string roleName{get;set;}
public string roleDescription{get;set;}
public ICollection<RoleGroup> roleGroups{get;set;}
}
我想要的是使用Id获取特定用户的所有角色
提前感谢。您可以看到从用户到角色的路径相当清晰: 用户->用户组->角色组角色 所以它不是很复杂,查询可以是这样的:
//with lazy loading enabled
var userRoles = context.Users.FirstOrDefault(e => e.Id == someId)
?.userGroups
?.SelectMany(e => e.group.roleGroups)
?.Select(e => e.role)?.ToList();
//with lazy loading disabled
var userRoles = context.Users.Where(e => e.Id == someId)
.SelectMany(e => e.userGroups)
.SelectMany(e => e.group.roleGroups)
.Select(e => e.role).ToList();
由于用户、组和角色表包含多对多关系,因此可以使用
Include
和thenclude
方法加载相关数据。检查以下查询语句:
//required using Microsoft.EntityFrameworkCore;
var result = (_context.User
.Include(c => c.userGroups)
.ThenInclude(c => c.group)
.ThenInclude(c => c.roleGroups)
.ThenInclude(c => c.role)
.Where(c=>c.Id ==1)
.SelectMany(c => c.userGroups.SelectMany(d => d.group.roleGroups
.Select(e => new { UserName = c.Username,
GroupName = e.group.groupName,
RoleName = e.role.roleName })))).ToList();
数据表如下所示(我们可以看到用户“Tom”有两个角色:“Admin”和“Manager”):
查询结果如下:
//with lazy loading enabled
var userRoles = context.Users.FirstOrDefault(e => e.Id == someId)
?.userGroups
?.SelectMany(e => e.group.roleGroups)
?.Select(e => e.role)?.ToList();
//with lazy loading disabled
var userRoles = context.Users.Where(e => e.Id == someId)
.SelectMany(e => e.userGroups)
.SelectMany(e => e.group.roleGroups)
.Select(e => e.role).ToList();
//with lazy loading enabled
var userRoles = context.Users.FirstOrDefault(e => e.Id == someId)
?.userGroups
?.SelectMany(e => e.group.roleGroups)
?.Select(e => e.role)?.ToList();
//with lazy loading disabled
var userRoles = context.Users.Where(e => e.Id == someId)
.SelectMany(e => e.userGroups)
.SelectMany(e => e.group.roleGroups)
.Select(e => e.role).ToList();
//required using Microsoft.EntityFrameworkCore;
var result = (_context.User
.Include(c => c.userGroups)
.ThenInclude(c => c.group)
.ThenInclude(c => c.roleGroups)
.ThenInclude(c => c.role)
.Where(c=>c.Id ==1)
.SelectMany(c => c.userGroups.SelectMany(d => d.group.roleGroups
.Select(e => new { UserName = c.Username,
GroupName = e.group.groupName,
RoleName = e.role.roleName })))).ToList();