0
class SomeObject
{
   public string name {get;set;}
}

class CustomCollection : List<SomeObject>
{
   public int x {get;set;}
   public string z {get;set;}
}

class A
{
   public CustomCollection collection { get ; set; }
}

class B
{
   public CustomCollection collection { get ; set; }
}


// Creating mapping   
Mapper.CreateMap<A, B>();

When I Map A to B, all properties get mapped correctly except X and Z in CustomCollection.

CustomCollection correctly gets the List of SomeObject initialized and SomeObject.Name is also mapped correctly.

Only the custom properties X, Z that I've declared in the collection do not get mapped.

What am I doing wrong?

Only way I've found is to do an after mapping like below, but then it kinda defeats the purpose of using automapper and it breaks everytime I add a new property to CustomCollection.

 Mapper.CreateMap<A, B>().AfterMap((source, destination) => { 
     source.x = destination.x; 
     source.z = destination.z ;
});
newbie
  • 1,485
  • 2
  • 18
  • 43

1 Answers1

0

Your current mapping configuration does create a new CustomCollection but the SomeObject items inside are references to the objects in the source collection. If that's not an issue you can use the following mapping configuration:

CreateMap<CustomCollection, CustomCollection>()
    .AfterMap((source, dest) => dest.AddRange(source));

CreateMap<A, B>();

If your are also fine with b.collection referencing to a.collection you could use the following mapping configuration:

CreateMap<CustomCollection, CustomCollection>()
    .ConstructUsing(col => col);

CreateMap<A, B>();

AutoMapper is not designed for cloning so if you need that you must write your own logic for that.

Martijn B
  • 4,065
  • 2
  • 29
  • 41
  • My issue is not if SomeObject do not get initialized or are references, but that CustomCollection.x and CustomCollection.y do not get mapped, they remain 0 and null respectively. – newbie Oct 29 '13 at 04:01