0

This is about Automapper 9. Let's say you have two classes like

public class Entity {
  public byte[] RowVersion { get; set; 
}
public class Model {
  public byte[] RowVersion { get; set; 
}
// mapping
CrateMap<Entity, Model>().ReverseMap();

When mapping, AutoMapper would simply copy array's reference to target. Which works for me, but only when projection is in direction from Entity to Model. When mapping Model back to Entity, I'd like to copy the array by value instead. Using a type converter won't work since it has collateral effects as it is a global converter. A value converter won't work either, since you can't access the target property, but just return a (new) instance of byte array. Ideally I would use a type converter on a CreateMap (without ReverseMap) but I doubt that's possible.

So I'm a bit stuck on how to do it properly.

Miha Markic
  • 3,158
  • 22
  • 28
  • 1
    To get the terminilogy right, you do not want a copy/shallow clone, but a deep clone. https://en.wikipedia.org/wiki/Cloning_(programming) – Christopher Oct 22 '19 at 08:28
  • Well, no. I don't want a clone in first place. I want array to be copied by value and not by reference. – Miha Markic Oct 22 '19 at 08:30
  • 3
    That is what we call a **deep clone/copy**. – MakePeaceGreatAgain Oct 22 '19 at 08:38
  • I have a target instance with an existing array, I have a source instance with an existing array. I want the values from source array to be copied into target instance instead. I consider clone to be a new instance with values copied, not a simple array copy operation. I could be wrong, but can we concentrate on solution instead. – Miha Markic Oct 22 '19 at 08:42
  • Also note that source and target types are different. – Miha Markic Oct 22 '19 at 08:44
  • Perhaps the projection in the caption was wrong, I meant mapping, not projection. Nevertheless this isn't cloning. – Miha Markic Oct 22 '19 at 08:54
  • The source and target types are different, but at some point some field (RowVersion) have exactly the same type (byte[]). And for this field, you want a cloning of values. – Pac0 Oct 22 '19 at 09:02
  • You could specify mapping for RowVersion manually (auto-mapper allows this) and create new instance of RowVersion in this case instead getting link – Oleg Bondarenko Oct 22 '19 at 09:13
  • I wish to preserve original target's byte[] instance though (and copy new values into it). – Miha Markic Oct 22 '19 at 09:16

1 Answers1

1

If I understand what you expect, I think you could use AfterMap to access both the source object and the destination object

this.CreateMap<Entity, Model>()
    .ReverseMap()
    .ForMember(destEntity => destEntity.RowVersion, opt => opt.Ignore())
    .AfterMap((srcModel, destEntity) =>
    {
        for (int i = 0; i < srcModel.RowVersion.Length; i++)
        {
            destEntity.RowVersion[i] = srcModel.RowVersion[i];
        }
    });
An0d
  • 213
  • 2
  • 12