Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to call Mapper.Map inside AfterMap?

Tags:

c#

automapper

Is something like this allowed somehow?

CreateMap<UserViewModel, User>()
    .ForMember(u => u.Password, o => o.Ignore())
    .AfterMap((src, dest) => {
        ...
        var entity = Mapper.Map<Entity>(src.SomeProperty);
        ...
    });

Is not working for me, it says that mapping tried to use inside AfterMap doesn't exist.

like image 978
StackOverflower Avatar asked Aug 28 '16 01:08

StackOverflower


People also ask

Does AutoMapper map both ways?

Yes, or you can call CreateMap<ModelClass, ViewModelClass>(). ReverseMap() .

How do I use AutoMapper to list a map?

How do I use AutoMapper? First, you need both a source and destination type to work with. The destination type's design can be influenced by the layer in which it lives, but AutoMapper works best as long as the names of the members match up to the source type's members.


1 Answers

I notice that you are using the static AutoMapper class within your mapping, but are you also using the static instance outside of your mapping and does it have a mapping configured for your Entity class?

The below works, note that the context.Mapper call ensures that the same AutoMapper instance is used for both the calling Map and subsequent AfterMap methods.

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<UserViewModel, User>()
       .AfterMap((source, destination, context) => 
       { 
            var entity = context.Mapper.Map<Entity>(source.SomeProperty);
       });

    cfg.CreateMap<EntityViewModel, Entity>();
});

var mapper = config.CreateMapper();

var viewModel = new UserViewModel
{
    Name = "Test User",
    SomeProperty = new EntityViewModel 
    { 
        Value = "Sub Class" 
    }
};

var user = mapper.Map<User>(viewModel);
like image 97
Johannes Kommer Avatar answered Oct 03 '22 04:10

Johannes Kommer