[Solved] Generic class of one type to another type in auto mapper


For Mapper.Map<PagedList<CasteModel>>(result);, you need to initialize Mapper like below in Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        Mapper.Initialize(cfg =>
        {
            cfg.AddProfile<AppProfile>();
        });
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

But, it it recommended to use Dependence Injection to resolve Mapper.

  1. Install Package AutoMapper.Extensions.Microsoft.DependencyInjection

  2. Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAutoMapper(typeof(Startup));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }
    
  3. UseCase

    public class ValuesController : ControllerBase
    {
        private readonly IMapper _mapper;
        public ValuesController(IMapper mapper)
        {
            _mapper = mapper;
        }
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            PagedList<Caste> result = new PagedList<Caste>
            {
                Items = new List<Caste> { new Caste { Id = 7, CasteCode = "" } },
                TotalItems = 1
            };
    
            var pagedListOfDtos = _mapper.Map<PagedList<CasteModel>>(result);
            return new string[] { "value1", "value2" };
        }       
    }
    

7

solved Generic class of one type to another type in auto mapper