Entity framework core 获取实体框架核心中包含主实体后的所有角色
我有三个实体,分别是Account、Role和AccountRole。通过repository模式,我获取了所有帐户、角色和AccountRole,如下所示: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); 现在,我想得到一个单一
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()