c# automapper nested object to flat object list

六眼飞鱼酱① 提交于 2019-12-13 05:06:06

问题


I have the following example structure:

public class Client
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<Adress> AdressList { get; set; }
}

public class Adress
{
     public Guid Id { get; set; }
     public string street { get; set; }
}

I want to automap this structure to something what normalizr does for javascript. I want to have a result that looks like this object

public class ViewModelRoot
{
     public ICollection<ViewModelClient> ViewModelClientList { get; set; }
     public ICollection<ViewModelAdress> ViewModelAdressList { get; set; }
}
public class ViewModelClient
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<string> AdressIdList { get; set; }
}

public class ViewModelAdress
{
     public Guid Id { get; set; }
     public string street { get; set; }
}

The mapping should extract the AdressList from my Client class to a seperate list on the same level and should replace the References with just its Guids.

I think that could be possible with AutoMapper ... any ideas? Thanks a lot in advance.


回答1:


Mapper.Initialize(cfg=>
{
    cfg.CreateMissingTypeMaps = false;
    cfg.CreateMap<Client, ViewModelRoot>()
        .ForMember(d=>d.ViewModelClientList, o=>o.MapFrom(s=>new[]{s}))
        .ForMember(d=>d.ViewModelAdressList, o=>o.MapFrom(s=>s.AdressList));
    cfg.CreateMap<Client, ViewModelClient>()
        .ForMember(d=>d.AdressIdList, o=>o.MapFrom(s=>s.AdressList.Select(a=>a.Id)));
    cfg.CreateMap<Adress, ViewModelAdress>();
});


来源:https://stackoverflow.com/questions/51451127/c-sharp-automapper-nested-object-to-flat-object-list

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