问题
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