将多个对象自动映射到一个对象

时间:2019-03-21 15:29:06

标签: automapper

我有以下源类别和目标类别:

        public class SourceData
    {
        public SourceMainData SourceMData { get; set; }
        public SourceOData OData { get; set; }
    }

    public class SourceMainData
    {
        public int Id { get; set; }
        public int SomeNumber { get; set; }

    }
    public class SourceOData
    {
        public string O1 { get; set; }
        public string O2 { get; set; }
        public int O3 { get; set; }
    }


    public class DestData
    {
        public int Id { get; set; }
        public int SomeNumber { get; set; }
        public DestOData OData { get; set; }

    }
    public class DestOData
    {
        public string O1 { get; set; }
        public string O2 { get; set; }
    }

我尝试使用以下内容,但是没有填充Id和SomeNumber属性:

            SourceData sourceData = new SourceData()
        {
            SourceMData = new SourceMainData()
            {
                Id = 3,
                SomeNumber = 5
            },
            OData = new SourceOData()
            {
                O1 = "OOOO1",
                O2 = "OOOOO2",
                O3 = 3
            }
        };

        var config = new MapperConfiguration(c =>
        {

            c.CreateMap<SourceMainData, DestData>();


            c.CreateMap<SourceData, DestData>()
                .ForMember(dest => dest.OData,
                    opt => opt.MapFrom(
                        source => source.OData));
        });

        var mapper = config.CreateMapper();
        var destData = mapper.Map<SourceData, DestData>(sourceData);
        Assert.Equal(5, destData.SomeNumber);

不知道我在做什么错。我本以为通过映射两个主要类,它将关联名为相同的字段并自动设置其值。

坦斯克 亚历克斯

0 个答案:

没有答案