Anele Ngqandu

Anele Ngqandu

  • 1.3k
  • 430
  • 28.6k

Create simple generic automapper in dotnet core 6

Mar 16 2023 5:47 AM

i am attempting to create a generic auto mapper, I want to map data from a Dto to a Database Entity.

Error I am getting is Unable to cast object of type 'System.Object' to type 'QuestionEntity'. Kindly assist. Using AutoMapper.Extensions.Microsoft.DependencyInjection 12.0.0

public class MappingService: IMappingService
{
    private readonly IMapper _mapper;

    public MappingService()
    {
        var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<object, object>();
            });

        _mapper = config.CreateMapper();
    }

    public TDestination Map<TDestination>(object source)
    {
        return _mapper.Map<TDestination>(source);
    }
}

Usage

var data = _mapperService.Map<QuestionEntity>(inputfromDto);

Answers (5)