C#ASP.NET Core AutoMapper:子对象为null

时间:2018-07-23 15:41:21

标签: c# asp.net-core automapper

我与用户和帐户之间存在多对多关系。

当我执行HttpGet时,我想返回AccountForDetailDto,其中包括一个ICollection<UserForListDto>,以列出与该帐户关联的用户。

我获得了附加到该帐户的用户的用户ID,但是User对象为空。

我假设我需要在某个地方做一个Include,但是我不确定在哪里。
我已经尝试过.Include(account => account.UserAccounts.Select(userAccounts => userAccounts.User)

或者我是否缺少地图/地图属性。

这就是我所拥有的:

AccountsController.cs

[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);
}


AccountRepository.cs

public async Task<Account> GetAccount(int id)
{
    return await _context.Accounts
        .Include(a => a.UserAccounts)
        .FirstOrDefaultAsync(a => a.Id == id);
}


AutoMapperProfiles.cs

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; }
}


Dtos

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; }
}

0 个答案:

没有答案