我与用户和帐户之间存在多对多关系。
当我执行HttpGet
时,我想返回AccountForDetailDto
,其中包括一个ICollection<UserForListDto>
,以列出与该帐户关联的用户。
我获得了附加到该帐户的用户的用户ID,但是User对象为空。
我假设我需要在某个地方做一个Include
,但是我不确定在哪里。
我已经尝试过.Include(account => account.UserAccounts.Select(userAccounts => userAccounts.User)
。
或者我是否缺少地图/地图属性。
这就是我所拥有的:
[HttpGet("{id}", Name = "GetAccount")]
public async Task<IActionResult> GetAccount(int id)
{
var accountFromRepo = await _repo.GetAccount(id);
var accountToReturn = _mapper.Map<AccountForDetailedDto>(accountFromRepo);
return Ok(accountToReturn);
}
public async Task<Account> GetAccount(int id)
{
return await _context.Accounts
.Include(a => a.UserAccounts)
.FirstOrDefaultAsync(a => a.Id == id);
}
CreateMap<UserAccount, UserForListDto>();
CreateMap<Account, AccountForDetailedDto>()
.ForMember(dto => dto.Users, opt => opt.MapFrom(a => a.UserAccounts));
public class Account
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<UserAccount> UserAccounts { get; set; }
}
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public ICollection<UserAccount> UserAccounts { get; set; }
}
public class UserAccount
{
public int? UserId { get; set; }
public User User { get; set; }
public int? AccountId { get; set; }
public Account Account { get; set; }
}
public class AccountForDetailedDto
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<UserForListDto> Users { get; set; }
}
public class UserForListDto
{
public int Id { get; set; }
public string Username { get; set; }
}