A better way to use AutoMapper to flatten nested objects?

前端 未结 7 1691
执笔经年
执笔经年 2020-12-28 15:02

I have been flattening domain objects into DTOs as shown in the example below:

public class Root
{
    public string AParentProperty { get; set; }
    public         


        
7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-28 15:24

    Not sure if this adds value to the previous solutions, but you could do it as a two-step mapping. Be careful to map in correct order if there are naming conflicts between the parent and child (last wins).

            Mapper.CreateMap();
            Mapper.CreateMap();
    
            var flattened = new Flattened();
            Mapper.Map(root, flattened);
            Mapper.Map(root.TheNestedClass, flattened);
    

提交回复
热议问题