Home > Software engineering >  AutoMapper - Map objects' properties (from object array to string array)
AutoMapper - Map objects' properties (from object array to string array)

Time:09-23

I have two similar objects that I am mapping to each other using AutoMapper. I create the map by doing the following:

CreateMap<Object1, Object2>()
   .ForMember(d => d.Name, o => o.MapFrom(s => s.Name))
   .ForMember(d => d.Description, o => o.MapFrom(s => s.Description))

Now Object1 has a property Object3[] listOfObject3 this Object3 has an Id property which I want to map to my Object2 property with string[] listOfObject3Ids

I tried the following but that doesn't work:

CreateMap<Object1, Object2>()
   .ForMember(d => d.Name, o => o.MapFrom(s => s.Name))
   .ForMember(d => d.Description, o => o.MapFrom(s => s.Description))
   .ForMember(d => d.listOfObject3.Id, o => o.MapFrom(s => new [] {s.Id})

How do I solve this?

CodePudding user response:

Besides @Sebastian's answer to work with System.Linq which is correct,

you can also work with .ConvertUsing() method.

  1. Create mapping from Object3 to string and via .ConvertUsing().

  2. Map member from Object1.listOfObject3 to Object2.listOfObject3Ids.

CreateMap<Object3, string>()
    .ConvertUsing((src) => src.Id);
            
CreateMap<Object1, Object2>()
    .ForMember(d => d.Name, o => o.MapFrom(s => s.Name))
    .ForMember(d => d.Description, o => o.MapFrom(s => s.Description))
    .ForMember(d => d.listOfObject3Ids, o => o.MapFrom(s => s.listOfObject3));

Demo @ .NET Fiddle


Reference

Custom Type Converters

CodePudding user response:

You can map like this:

    CreateMap<Object1, Object2>()
        .ForMember(d => d.Name, o => o.MapFrom(s => s.Name))
        .ForMember(d => d.Description, o => o.MapFrom(s => s.Description))
        .ForMember(d => d.ListOfObject3, o => o.MapFrom(s => s.listOfObject3Ids.Select(id => new Object3 { Id = id })));

But as I already commented I am assuming your Object2 contains the list of Object3 and your Object1 contains the list with the ids. Then you could map like this:

CreateMap<Object1, Object2>()
                .ForMember(d => d.Name, o => o.MapFrom(s => s.Name))
                .ForMember(d => d.Description, o => o.MapFrom(s => s.Description))
                .ForMember(d => d.listOfObject3Ids, o => o.MapFrom(s => s.ListOfObject3.Select(o => o.Id)));
  • Related