在包含 Entity framework 核心中的主要实体后获取所有角色

Get all the roles after include with main entity in Entity framework Core

我有三个实体,分别是帐户、角色和帐户角色。通过存储库模式,我已经获取了所有帐户、角色和帐户角色,如下所示:

var accounts = _accountRepository.Query()
                .Include(x => x.AccountRoles)
                    .ThenInclude(x => x.Role);
                

现在我想获得一个包含所有角色的帐户信息。所以我写了下面的查询。 但问题只是第一个角色出来

var userAccount = accounts.Where(x => x.Id == id)
                                    .Select(x => new AccountDto
                                    {
                                        Id = x.Id,
                                        Name = x.UserFullName,
                                        FirstName = x.FirstName,
                                        LastName = x.LastName,
                                        Email = x.Email,
                                        Mobile = x.Mobile,
                                        UserName = x.UserName,
                                        PhotoUrl = x.PhotoUrl,
                                        IsActive = x.IsActive,
                                        Roles = accounts.Where(x => x.Id == id).Select(x => new RoleDto
                                        {
                                            Title = x.AccountRoles
                                                    .Where(x => x.IsActive == true)
                                                    .Select(x => x.Role.Title).FirstOrDefault()
                                        }).ToList()
                                    }).FirstOrDefault();

谁能帮我写出正确的查询?

首先是这部分

Roles = accounts.Where(x => x.Id == id).Select(x => new RoleDto
{
    Title = x.AccountRoles
            .Where(x => x.IsActive == true)
            .Select(x => x.Role.Title).FirstOrDefault()
}).ToList()

是一种很奇怪的混合体,你应该简单地使用导航 属性(是的,它不仅像某些人认为的那样用于包含)。

其次,如果您想获得所有项目而不是第一个项目,请不要应用 FirstOrDefault()

// here x variable type is Account (coming from the outer Select)
Roles = x.AccountRoles
    .Where(ar => ar.IsActive)
    .Select(ar => new RoleDto
    {
        Title = ar.Role.Title,
    }).ToList()