我一直熬到凌晨 1 点,试图找出我遇到的一个主要障碍。我在网上找不到任何东西,也无法想出解决办法。在收到同事的反馈后,...
我一直熬到凌晨 1 点,试图解决我遇到的一个主要障碍。我在网上找不到任何东西,也无法想出解决办法。
在得到同事的一些反馈后,问题在于需要一个原始 SQL 来映射用户角色。
这就是我被难倒的地方。我不太熟悉编写原始调用,所以是的。如果有人对此有任何指导,我将不胜感激!这是我在 StackOverflow 上的第一篇帖子,所以如果这不是格式化我的问题的最佳方式,我深表歉意
此外,对于一个刚进入该领域 7 个月的初级 .NET Core 开发人员来说,这种级别的 SQL 知识是否常见/预期?
这与我的 NotifyManagers
和 NotifyUsers
据我所知, allClientUsers
我无法在初始调用 (?) 时获取它们
allClientUsers
正在为列表返回一个值,但是当它到达下一个时,它始终返回 null。
这是所有相关信息,需要注意的是,这是一个.NET Core 应用程序。
if (entity.NotifyManagers is true || entity.NotifyUsers is true)
{
List<ApplicationUser> allClientUsers = await DbContext.Users
.Where(x => x.ClientId == entity!.Dashboard!.ClientId)
.ToListAsync();
// callCoachingManagers still returning null :(
List<ApplicationUser> callCoachingManagers = allClientUsers
.Where(x => x.Roles != null && x.Roles.Contains("Call Coaching Manager"))
.ToList();
List<ApplicationUser> callCoachingUsers = allClientUsers
.Where(x => x.Roles!.Contains("Call Coaching User"))
.ToList();
List<ApplicationUser> recipients = [];
if (callCoachingManagers.Count != 0 && entity.NotifyManagers is true)
{
recipients.AddRange(callCoachingManagers);
}
if (callCoachingUsers.Count != 0 && entity.NotifyUsers is true)
{
recipients.AddRange(callCoachingUsers);
}
}
[NotMapped]
public List<string>? Roles { get; set; }
用户控制器中的类似调用
string[] arrayOfIds = [.. entities.Select(x => x.Id)];
string? connectionString = Configuration.GetConnectionString("DefaultConnection");
List<UserRoleMapping> userRoleMappings = [];
string sqlQuery = "SELECT u.Id AS UserId, STRING_AGG(r.Name, ', ') AS Roles " +
"FROM AspNetUsers u " +
"JOIN AspNetUserRoles ur ON u.Id = ur.UserId " +
"JOIN AspNetRoles r ON ur.RoleId = r.Id " +
(filter ? " And u.Id in @ids " : "") +
"GROUP BY u.id";
using (SqlConnection sqlConnection = new(connectionString))
{
userRoleMappings = sqlConnection.Query<UserRoleMapping>(sqlQuery, filter ? new { ids = arrayOfIds } : null).ToList();
}
entities = (from entity in entities.ToList()
join mapping in userRoleMappings on entity.Id equals mapping.UserId into g
from x in g.DefaultIfEmpty()
select new ApplicationUser
{
Active = entity.Active,
Client = entity.Client,
ClientId = entity.ClientId,
ClientIds = entity.ClientIds,
DateCreated = entity.DateCreated,
DateModified = entity.DateModified,
Email = entity.Email,
FirstName = entity.FirstName,
Id = entity.Id,
LastName = entity.LastName,
LoginCount = entity.LoginCount,
LoginDate = entity.LoginDate,
RoleList = x == null ? string.Empty : x.Roles
})
.OrderBy(x => x.FirstName).ThenBy(x => x.LastName)
.AsQueryable();
如果还需要什么来理解这些垃圾,请告诉我