Home > Software design >  AutoMapper setting EF entity ID to 0 during mapping
AutoMapper setting EF entity ID to 0 during mapping

Time:09-20

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?

CodePudding user response:

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

  • Related