簡體   English   中英

AutoMapper - Map 將 object 展平為復雜的 object

[英]AutoMapper - Map flatten object to complex object

我有這些模型:

class Source
{
    String A;
    String B;
    String C;
    String D;
}

class Destination
{
    String A;
    String B;
    Another another;
    Other other;
}

class Other
{
    String C;
    AnotherOne Another;
}

class AnotherOne
{
    String D;
}

我想 map Source model 到Destination及其子級。 嘗試使用 AutoMapper 的第一種方法。 那么有可能嗎? 還是手動完成這項任務更好?

解決方案 1:使用ForPath

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Source, AnotherOne>();
            
    cfg.CreateMap<Source, Other>()
        .ForPath(dest => dest.Another, opt => opt.MapFrom(src => src));
            
    cfg.CreateMap<Source, Destination>()
        .ForPath(dest => dest.other, opt => opt.MapFrom(src => src));
});

演示解決方案 1 @ .NET 小提琴


解決方案 2:使用IncludeMembersReverseMap顯式創建反向 map。

var config = new MapperConfiguration(cfg =>
{           
    cfg.CreateMap<Source, AnotherOne>()
        .ReverseMap();
            
    cfg.CreateMap<Other, Source>()
        .IncludeMembers(src => src.Another)
        .ReverseMap();
            
    cfg.CreateMap<Destination, Source>()
        .IncludeMembers(src => src.other)
        .ReverseMap();
});

演示解決方案 2 @ .NET 小提琴


參考

展平(IncludeMembers 部分) - AutoMapper 文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM