Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework core 获取实体框架核心中包含主实体后的所有角色_Entity Framework Core_Repository Pattern - Fatal编程技术网

Entity framework core 获取实体框架核心中包含主实体后的所有角色

Entity framework core 获取实体框架核心中包含主实体后的所有角色,entity-framework-core,repository-pattern,Entity Framework Core,Repository Pattern,我有三个实体,分别是Account、Role和AccountRole。通过repository模式,我获取了所有帐户、角色和AccountRole,如下所示: var accounts = _accountRepository.Query() .Include(x => x.AccountRoles) .ThenInclude(x => x.Role); 现在,我想得到一个单一

我有三个实体,分别是Account、Role和AccountRole。通过repository模式,我获取了所有帐户、角色和AccountRole,如下所示:

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()