我跟随Linq查询来获取User并添加UserClaimCollection。
public async Task<List<User>> GetCollection()
{
List<User> result = _identityContext.Users
.GroupJoin(
_identityContext.UserClaims,
u => u.Id,
uc => uc.UserId,
(u, uc) => new { user = u, claims = uc })
.ToList()
.Select(u => new User(
new Guid(u.user.Id),
u.user.UserName,
u.user.FirstName,
u.user.LastName,
u.user.Email,
new UserClaimCollection(
u.claims.Select(uc => new UserClaim(uc.ClaimType, uc.ClaimValue)).ToList()
))
).ToList();
return result;
}
如何将第二个GroupJoin添加到此选择中以添加角色集合?
例如
public async Task<List<User>> GetCollection()
{
List<User> result = _identityContext.Users
.GroupJoin(
_identityContext.UserClaims,
u => u.Id,
uc => uc.UserId,
(u, uc) => new { user = u, claims = uc })
.GroupJoin(
_identityContext.UserRoles,
u => u.Id,
ur => ur.UserId,
(u, ur) => new { user = u, roles= ur })
.ToList()
.Select(u => new User(
new Guid(u.user.Id),
u.user.UserName,
u.user.FirstName,
u.user.LastName,
u.user.Email,
new UserClaimCollection(
u.claims.Select(uc => new UserClaim(uc.ClaimType, uc.ClaimValue)).ToList()
)),
new UserRoleCollection(
u.roles.Select(ur => new UserRole(ur.RoleType, ur.RoleValue)).ToList()
))
).ToList();
return result;
}
答案 0 :(得分:1)
您需要记住第一个GroupJoin
的输出是您的新匿名类,因此您就是将其传递给第二个GroupJoin
的内容。我建议命名lambda参数以提醒您这一点。
List<User> result = _identityContext.Users
.GroupJoin(
_identityContext.UserClaims,
u => u.Id,
c => c.UserId,
(user, claims) => new { user, claims })
.GroupJoin(
_identityContext.UserRoles,
uc => uc.user.Id,
roles => roles.UserId,
(uc, roles) => new { uc.user, uc.claims, roles })
.ToList()
.Select(ucr => new User(
new Guid(ucr.user.Id),
ucr.user.UserName,
ucr.user.FirstName,
ucr.user.LastName,
ucr.user.Email,
new UserClaimCollection(
ucr.claims.Select(c => new UserClaim(c.ClaimType, c.ClaimValue)).ToList()
)),
new UserRoleCollection(
ucr.roles.Select(r => new UserRole(r.RoleType, r.RoleValue)).ToList()
))
).ToList();