Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper: using BeforeMap and AfterMap

Tags:

c#

automapper

I am using automapper (successfully up to a point) to perform a polymorphic map between two interfaces like so:

configure.CreateMap<IFrom, ITo>()
    .Include<FromImplementation1, ToImplementation1>()
    .Include<FromImplementation2, ToImplementation2>()
    ... ;

This works fine. In addition however, the interfaces include method signatures, the implementations of which are intended to modify the objects before mapping:

public interface IFrom
{
    void PrepareForMapping();
}

As you can see the method has no return but is designed to modify the state of the object before the mapping is performed. At present this method is called manually before the object is mapped, but my intention was to execute the method automatically before the mapping takes place. I attempted to use it as follows:

configure.CreateMap<IFrom, ITo>()
    .BeforeMap((x,y) => x.PrepareForMapping())
    .Include<FromImplementation1, ToImplementation1>()
    .Include<FromImplementation2, ToImplementation2>()
    ... ;

However the method is never being called, although the mapping itself is still working fine. I have placed breakpoints on every implementation of the PrepareForMapping() method and none of them are getting hit. So I came to the conclusion that I have either misunderstood how BeforeMap/AfterMap work, or I am doing something wrong (or both).

Many thanks.

like image 717
Nigel Avatar asked May 10 '10 21:05

Nigel


People also ask

When should you not use AutoMapper?

If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.

Is it good to use AutoMapper?

AutoMapper is a great tool when used for simple conversions. When you start using more complex conversions, AutoMapper can be invaluable. For very simple conversions you could of course write your own conversion method, but why write something that somebody already has written?

Does AutoMapper work with .NET core?

AutoMapper is a ubiquitous, simple, convention-based object-to-object mapping library compatible with.NET Core. It is adept at converting an input object of one kind into an output object of a different type. You can use it to map objects of incompatible types.


1 Answers

For this one, you'll have to put the Before/After map on the derived types. This is because Include redirects the map to the polymorphic types. It's not an additive configuration, the Included maps replace the configuration.

like image 141
Jimmy Bogard Avatar answered Sep 28 '22 09:09

Jimmy Bogard