automapper multi objects to one object

馋奶兔 提交于 2019-12-19 07:09:14

问题


I have two sub class that I need to copy a List element from into a master object

public Class Foo1 : Anote
{
  public bool Ison { get; set;}
  public List<Anote>Anotes { get; private set;}

  public Foo1()
  {
    this.Anotes = new List<Anote>();
  }
}

public Class Foo2 : Bnote
{
  public bool Ison { get; set;}
  public List<Bnote>Anotes { get; private set;}

  public Foo2()
  {
    this.Anotes = new List<Bnote>();
  }
}

public Class Foo3 : Cnote
{
   public bool Ison { get; set;}
   public List<Cnote>Anotes { get; private set;}
   public List<Cnote>Bnotes { get; private set; }

}

I will be retreiving data from a database and putting this data into Foo1 and Foo2. I then need to Map the List data from Foo1 and Foo2 into the List elements in Foo3.

I have done

Foo1A foo1a = new Foo1A();
Foo2A foo2a = new Foo2A();

Mapper.CreateMap<Foo1, Foo1A>();
Mapper.CreateMap<Foo2, Foo2A>();
Mapper.Map<Foo1, Foo2A>(foo1, foo1a);
Mapper.Map<Foo2, Foo2A>(foo2, foo2a);

and this works but what I need to do is

Map the List Anotes in Foo1 to the List Anotes in Foo3 Map the List Anotes in Foo2 to the List Bnotes in Foo3.


回答1:


You should just be able to do:

Mapper.CreateMap<ANote, CNote>();

Mapper.CreateMap<Foo1, Foo3>()
    .ForMember(dest => dest.ANotes, opt => opt.MapFrom(src => src.ANotes))
    .ForMember(dest => dest.BNotes, opt => opt.Ignore());

Mapper.CreateMap<Foo2, Foo3>()
    .ForMember(dest => dest.BNotes, opt => opt.MapFrom(src => src.ANotes))
    .ForMember(dest => dest.ANotes, opt => opt.Ignore());

Foo3 foo3 = new Foo3();

Mapper.Map<Foo1, Foo3>(foo, foo3);
Mapper.Map<Foo2, Foo3>(foo2, foo3);

foo3.ANotes and foo3.BNotes should both have been mapped correctly.



来源:https://stackoverflow.com/questions/12429210/automapper-multi-objects-to-one-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!