A better way to use AutoMapper to flatten nested objects?

前端 未结 7 1624
执笔经年
执笔经年 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:41

    2 more possible solutions:

    Mapper.CreateMap<Nested, Flattened>()
        .ForMember(s=>s.AParentProperty, o=>o.Ignore());
    Mapper.CreateMap<Root, Flattened>()
        .ForMember(d => d.ANestedProperty, o => o.MapFrom(s => s.TheNestedClass));
    

    An alternative approach would be the below, but it would not pass the Mapper.AssertConfigurationIsValid().

    Mapper.CreateMap<Nested, Flattened>()
    //.ForMember map your properties here
    Mapper.CreateMap<Root, Flattened>()
    //.ForMember... map you properties here
    .AfterMap((s, d) => Mapper.Map(s.TheNestedClass, d));
    
    0 讨论(0)
提交回复
热议问题