Home > Net >  AutoMapper is not including the GetUserDto in response
AutoMapper is not including the GetUserDto in response

Time:05-08

AutoMapper Class:

namespace ef_practice
{
    public class AutoMapperProfile : Profile
    {
        public AutoMapperProfile()
        {
            CreateMap<Character, GetCharacterDto>();
            CreateMap<AddCharacterDto, Character>();
            CreateMap<Weapon, GetWeaponDto>();
            CreateMap<User, GetUserDto>();
        }
    }
}

Service Layer:

public async Task<ServiceResponse<GetCharacterDto>> GetSingle(int id)
        {
            var serviceResponse = new ServiceResponse<GetCharacterDto>();
            var dbCharacter = await _context.Characters
            .Include(c => c.User)
            .FirstOrDefaultAsync(ele => ele.Id == id && ele.User.Id == 1);
            serviceResponse.Data = _mapper.Map<GetCharacterDto>(dbCharacter);
            return serviceResponse;
        }

GetCharacterDto Class:

public class GetCharacterDto
    {
        public int Id { get; set; }
        public string Name { get; set; } = "Frodo";
        public int HitPoints { get; set; } = 100;
        public int Strength { get; set; } = 10;
        public int Defense { get; set; } = 10;
        public int Intelligence { get; set; } = 10;
        public RpgClass Class { get; set; } = RpgClass.Knight;
        public GetUserDto User = new GetUserDto();
    }

GetUserDto Class:

namespace ef_practice.Dtos.User
{
    public class GetUserDto
    {
        public int Id { get; set; }
        public string Username { get; set; } = "";
    }
}

Response:

{
  "data": {
    "id": 2,
    "name": "string",
    "hitPoints": 0,
    "strength": 10,
    "defense": 0,
    "intelligence": 0,
    "class": 0
  },
  "success": true,
  "message": ""
}

Response data is of model GetCharacterDto which has GetUserDto but in the response User object is not included. I am not sure whats going wrong here. Can anyone help me with the solution.

CodePudding user response:

In GetCharacterDto class, User is a field but not a property.

Change it to the property by adding getter and setter.

public class GetCharacterDto
{
    ...

    public GetUserDto User { get; set; } = new GetUserDto();
}
  • Related