A better way to use AutoMapper to flatten nested objects?

前端 未结 7 1719
执笔经年
执笔经年 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条回答
  •  梦毁少年i
    2020-12-28 15:30

    In the latest version of AutoMapper, there's a naming convention you can use to avoid multiple .ForMember statements.

    In your example, if you update your Flattened class to be:

    public class Flattened
    {
        public string AParentProperty { get; set; }
        public string TheNestedClassANestedProperty { get; set; }
    }
    

    You can avoid the use of the ForMember statement:

    Mapper.CreateMap();
    

    Automapper will (by convention) map Root.TheNestedClass.ANestedProperty to Flattened.TheNestedClassANestedProperty in this case. It looks less ugly when you're using real class names, honest!

提交回复
热议问题