Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper does not map base

Tags:

c#

automapper

Hi i am having some trouble making my mapping work in automapper.

I have 2 DTOs BaseDto and BaseOrganizationDto

public class BaseDto
{}

public class SensitiveBaseDto : BaseDto
{}

I use the following mappings:

CreateMap<IEntity, BaseDto>()
                .Include<IEntity, SensitiveBaseDto>()
                .IncludeBase<IEntity, BaseDto>();

I try to get a certain dto based on some logic like

public BaseDto MapToDto(Guid asSeenById, IEntity entity)
    if (entity.Id != asSeenById)
    {
      return this.MapToDto<BaseDto>(entity);
    }
    return this.MapToDto<SensitiveBaseDto>(entity);
}

But it always returns a SensitiveBaseDto, I have validated that the logic in the MapToDto method is executes properly.

What am I missing?

like image 221
Rune Jensen Avatar asked Feb 12 '26 00:02

Rune Jensen


1 Answers

Solved it by doing this:

public override TDtoType MapToDto<TDtoType>(IEntity entity)
{
    var dto = typeof(TDtoType) == typeof(SensitiveDto) 
        ? new SensitiveDto() 
        : new BaseDto();

    this.Engine.Map(entity, dto);
    return dto as TDtoType;
}
like image 198
Rune Jensen Avatar answered Feb 14 '26 14:02

Rune Jensen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!