9

Mapper Automap:

Mapper.CreateMap<ObjectType1, ObjectType2>()
    .ForMember(o1 => o1.PropName, mapper => mapper.MapFrom(o2 => o2.Prop2Name));

Mapper.Map(object1, object2);

Implicit operator:

public static implicit operator Object1(Object2 o2)
{ 
    Object1 o1 = new Object2(); 
    //Mapping code here...
    return o1;
}
David Pfeffer
  • 38,869
  • 30
  • 127
  • 202
Boanerge
  • 369
  • 2
  • 15
  • 1
    I read this a while ago. http://stackoverflow.com/questions/13053590/emit-mapper-vs-valueinjecter-or-automapper-performance – Christian Lennartsson Mar 10 '13 at 18:08
  • Quick preview of @ChristianLennartsson's link... With EmitMapper: Auto Mapper (simple): **38483 milliseconds**, Emit Mapper (simple): **118 milliseconds**, Handwritten Mapper (simple): **37 milliseconds**. Explanation from EmitMapper: "_[EmitMapper] effectively uses the Emit library to generate mappers at run-time direct in IL as though these mappers are written by hand. Most other mappers use the Reflection library for mapping (or source code generation)._" Obviously several years old at this point, but worth a read. – ruffin Sep 29 '20 at 23:46

1 Answers1

8

There's no reason you couldn't use both together, by calling Mapper.Map from the implicit operator.

Using AutoMapper allows you to rely on automatically generated mapping code, so that you don't have to use ForMember to map each member individually.

David Pfeffer
  • 38,869
  • 30
  • 127
  • 202
  • What about performance? I think that doing everything in the implicit operator is faster, but I haven't tested it myself. – Boanerge Mar 11 '13 at 17:19
  • I would imagine AutoMapper is slower, but we're talking about minor differences. – David Pfeffer Mar 11 '13 at 17:21
  • 1
    OK. Thanks for your FAST response. – Boanerge Mar 11 '13 at 17:22
  • At the risk of sounding as if I question your answer (which I certainly do **not** intend to), I wonder: if wrapping the `Mapper.Map(source)` in an implicit/explicit operator for conversion is wise, why not more people do that as a default approach? The advantage would be cleaner code and ease of reading as well as compartmentalization of concerns. What's the drawback preventing people from going full metal jacket into this strategy? – Konrad Viltersten Jul 11 '23 at 08:50
  • @KonradViltersten People do not in general like implementing either the implicit conversion operator because it doesn't make it clear that you are converting between incompatible types. One might surmise from reading code with an implicit conversion that the types are compatible through inheritance. – David Pfeffer Jul 11 '23 at 21:07