简体   繁体   中英

AutoMapper map one list to two equally sized lists with derived properties

So I have a source object with one list, the list includes two types of values but I would like for the destination to have two list, one for each value but in the same resulting property. I hope the example here is self explanatory.

My Source:

    public class SourceObject
    {
        public SourceObject()
        {
            SourceList = new List<AnotherSourceObject>();
        }

        public IList<AnotherSourceObject> SourceList { get; private set; }

        //some other properties
    }

    public class AnotherSourceObject
    {
        public int Number { get; set; }
        public decimal Value1 { get; set; }
        public decimal Value2 { get; set; }
        public decimal Total { get; set; }
    }

My Destination:

    public class DestObject
    {
        public DestObject()
        {
            ValueOneList = new List<AnotherDestObject>();
            ValueOneList = new List<AnotherDestObject>();
        }

        public IList<AnotherDestObject> ValueOneList { get; private set; }
        public IList<AnotherDestObject> ValueTwoList { get; private set; }

        //some other properties that map perfectly
    }

    public class AnotherDestObject
    {
        public int Number { get; set; }
        public decimal Value { get; set; }
    }

My Automapper mapping:

    Mapper.CreateMap<Source, DestObject>()
        .ForMember(dest => dest.ValueOneList, opt => opt.MapFrom(source => source.SourceList)) //get value1 to Value
        .ForMember(dest => dest.ValueTwoList, opt => opt.MapFrom(source => source.SourceList))  //get value2 to Value

You can use AfterMap if you have accidentally made setters private :

Mapper.CreateMap<Source, DestObject>()
     .AfterMap((src, dest) =>
     {
         foreach (var item in src.SourceList)
         {
             dest.ValueOneList.Add(new AnotherDestObject { Number = item.Number, Value = item.Value1 });
             dest.ValueTwoList.Add(new AnotherDestObject { Number = item.Number, Value = item.Value2 });
         }
     });

If setter must be private , then you must add new constructor to your class and use ConstructUsing() .

Add this constructor:

  public DestObject(List<AnotherSourceObject>() sourceList)
    {
        ValueOneList = sourceList.Select(x => new AnotherDestObject { Number = item.Number, Value = item.Value1 }).ToList();
        ValueTwoList = sourceList.Select(x => new AnotherDestObject { Number = item.Number, Value = item.Value2 }).ToList();
    }

And, then:

Mapper.CreateMap<Source, DestObject>()
            .ConstructUsing(src => new DestObject(src.SourceList));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM