c# automapper nested object to flat object list

2019-08-20 09:18发布

问题:

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>();
});