簡體   English   中英

AutoMapper:將嵌套對象映射到平面

[英]AutoMapper: map nested object to flat

我已經定義了從一種類型到 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”的定義映射?

謝謝!

首先,感謝 Lucian Bargaoanu 帶領我走向正確的方向。 基本上,您需要創建從源到目標派生類型的映射,但只需包含現有映射。

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

cfg.CreateMap<SecondDataType, SecondTypeDto>()
                .IncludeMembers(s => s.FirstData)                    
                .ReverseMap();

暫無
暫無

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

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