0

I have a Character entity and a CharacterDto as follows:

Character

public class Character
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public int Health { get; set; } = 100;
    public int Defense { get; set; } = 10;
    public int Strength { get; set; } = 10;
    public int Intelligence { get; set; } = 10;
    public RpgClass Class { get; set; }
}

CharacterDto

public class CharacterDto
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public int Health { get; set; }
    public int Defense { get; set; }
    public int Strength { get; set; }
    public int Intelligence { get; set; }
    public RpgClass Class { get; set; }
}

I have a CharacterMappingProfile class which configures my Character and DTO mappings:

CreateMap<CharacterDto, Character>()
  .ForMember(
    dest => dest.Id,
    opt => opt.Ignore()
  );

I am attempting to map the values present in a CharacterDto onto an existing Character entity I have retried from a database using EntityFramework.

var character = _context.FirstOrDefaultAsync(...);
character = _mapper.Map<Character>(dto);

Prior to performing the map, character has a valid Id property. However, after the map the value is 0 which is not what I want. I would like AutoMapper to ignore that property and for it to therefore remain whatever the value is from the database. I must be misunderstanding how the ForMember with Ignore works as I thought that would do the trick.

Have I configured my mapping incorrectly or am I going wrong elsewhere?

Ruben Hart
  • 59
  • 8

1 Answers1

0

To map a CharacterDto to an existing Character object you need to use:

var character = _context.FirstOrDefaultAsync(...);
_mapper.Map(dto, character);

Right now _mapper.Map<Character>(dto); is mapping your dto to a new empty Character instance and then you are assigning it to the character variable. That's why Id property is 0.

Automapper: Update property values without creating a new object

Dimitris Maragkos
  • 8,932
  • 2
  • 8
  • 26
  • Thanks, `_mapper.Map(dto, character);` solved it. I had tried providing the existing `Character` as a second parameter in the `Map` function, but not without ``. – Ruben Hart Sep 19 '22 at 21:43