Search code examples
c#asp.net-mvcautomapper-5

AutoMapper 5.1 - Map Model and extended Model


I'm new with AutoMapper and i'm using 5.1.1 version. I tried to map a list of model with a list of extended model. I get empty object in return.

My source model

public class spt_detail
{
    public string Name { get; set; }
    public string Age { get; set; }
}

My destination model

public class spt_detail_extended : spt_detail
{   
    public string Mm1 { get; set; }
    public string Mm2 { get; set; }
}

AutoMapper code

spt_detail details = db.spt_detail.ToList();

Mapper.Initialize(n => n.CreateMap<List<spt_detail>, List<spt_detail_extended>>());
List<spt_creance_detail_enrichi> cenr = AutoMapper.Mapper.Map<List<spt_detail>, List<spt_detail_enrichi>>(details);

Issue : details contains 8 rows but cenr 0.

Someone can helps me ?


Solution

  • Mapping for spt_detail to spt_detail_extended.

    You should create map rules only for models, like that:

    Mapper.Initialize(cfg =>
    {
        cfg.CreateMap<spt_detail, spt_detail_extended>();
    });
    

    And after that, you hould use the construction:

    List<spt_detail_extended> extendeds = Mapper.Map<List<spt_detail_extended>>(details);
    

    If you want to map other models, just add or edit your configuration.