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.
Yes, or you can call CreateMap<ModelClass, ViewModelClass>(). ReverseMap() .
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With