简体   繁体   English

如何使用自动映射器跳过对象

[英]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: 以及以下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. 我想做一些自动映射,要做到这一点,我必须跳过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. 但这总是给我提供Missing type map configuration or unsupported mapping. exception. 例外。

You can tell Automapper to ignore them if you want to skip the object: 如果要跳过对象,可以告诉Automapper忽略它们:

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: 但是通过您给出的示例,您可能想要创建另一个地图,以便Notes也可以自动映射:

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) (示例使用System.Linq)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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