简体   繁体   中英

How to skip an object using the automapper

I've got the following DataModels:

class TicketDM
{
 public int Id{get;set;}
 public List<NoteContractDM> Notes{get;set;}
}

class NoteContractDM
{
 public NoteDM Note{get;set;}
}

class NoteDM{
 public string Subject{get;set;}
 public string Description{get;set}
}

And the following ViewModels:

public class TicketVM
{
 public int Id {get;set;
 public List<NoteVM> Notes{get;set;}
}

public NoteVM
{
 public string Subject{get;set;}
 public string Description{get;set;}
} 

I want to do some automapping, and to do that I have to skip the noteContractDM. The following obviously doesnt work:

Mapper.CreateMap<TicketDM, TicketVM>()

I tried something like this:

Mapper.CreateMap<TicketDM, TicketVM>()
  .ForMember(vm => vm.Notes, conf => conf.MapFrom(dm => dm.Notes));  

But it always gives me the Missing type map configuration or unsupported mapping. exception.

You can tell Automapper to ignore them if you want to skip the object:

Mapper.CreateMap<TicketDM, TicketVM>()
.ForMember(vm => vm.Notes, conf => conf.Ignore());  

But by the example you are giving, you may want to create another map so Notes can also get mapped automatically:

Mapper.CreateMap<TicketDM, TicketVM>()
.ForMember(vm => vm.Notes, conf => conf.MapFrom(dm => dm.Notes.Select(x => x.Note)));

Mapper.CreateMap<NoteDM, NoteVM>();

(example uses System.Linq)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM