AutoMapper:将嵌套对象映射到平面

问题描述 投票:1回答:1

我已经定义了从一种类型到DTO的映射。另一种类型将第一种类型引用为属性,但是输出应该是扁平化的DTO,该DTO应该使用已经定义的第一种类型的映射。

class Program {
    static void Main(string[] args) {
        var mapperConfiguration = new MapperConfiguration(cfg => {
            cfg.CreateMap<FirstDataType,
            FirstTypeDto>().ForMember(d => d.TypeResult, opt => opt.MapFrom(s => s.ToString()));

            /* HOW TO CONFIGURE MAPPING OF THE 'FirstData' PROPERTY TO USE THE ABOVE DEFINED MAPPING
                cfg.CreateMap<SecondDataType, SecondTypeDto>()
                */
        });

        var firstData = new FirstDataType {
            TypeName = "TestType",
            TypeValue = "TestValue"
        };

        var secondData = new SecondDataType {
            Id = 1,
            Name = "Second type",
            FirstData = firstData
        };

        var mapper = mapperConfiguration.CreateMapper();

        var firstDto = mapper.Map<FirstTypeDto>(firstData);
        var secondDto = mapper.Map<SecondTypeDto>(secondData);

        Console.ReadKey(true);
    }
}

public class FirstDataType {
    public string TypeName {
        get;
        set;
    }

    public string TypeValue {
        get;
        set;
    }

    public override string ToString() {
        return $ "{TypeName}: {TypeValue}";
    }
}

public class SecondDataType {
    public int Id {
        get;
        set;
    }

    public string Name {
        get;
        set;
    }

    public FirstDataType FirstData {
        get;
        set;
    }
}

public class FirstTypeDto {
    public string TypeName {
        get;
        set;
    }

    public string TypeValue {
        get;
        set;
    }

    public string TypeResult {
        get;
        set;
    }
}

public class SecondTypeDto: FirstTypeDto {
    public int Id {
        get;
        set;
    }

    public string Name {
        get;
        set;
    }
}

我应如何配置第二种类型的映射以将定义的映射用于属性'FirstData'?

谢谢!

c# .net-core automapper automapper-6
1个回答
0
投票

首先,感谢Lucian Bargaoanu带领我朝着正确的方向前进。基本上,您需要创建一个从源到目标派生类型的映射,但只需包含现有映射即可。

cfg.CreateMap<FirstDataType, SecondTypeDto>()
                .IncludeBase<FirstDataType, FirstTypeDto>()
                .ReverseMap();

cfg.CreateMap<SecondDataType, SecondTypeDto>()
                .IncludeMembers(s => s.FirstData)                    
                .ReverseMap();
© www.soinside.com 2019 - 2024. All rights reserved.