percentum
percentum

Reputation: 153

AutoMapper: ignore property on update existing, but allow when create

Is it possible to configure/use AutoMapper in such a way where when i create an object from a mapping i allow all properties and child collections, however, when it comes to performing an update to existing object, the mapping will ignore child collection properties as they will be empty but i dont want them removed.

This is because i am working with a WCF service that sends delta changes to objects and most of my model works in a tree hierarchy:

Parent
  List<Child> Children

ParentDto
  List<ChildDto> Children

config.CreateMap<ParentDto, Parent>();
config.CreateMap<ChildDto, ChildDto>();

This works well and the child collection is populated first time round. However, there are scenarios where i will send the ParentDto across with just the parent POCO property changes (such as a datetime change), but the child list will be empty as none of them have changed. Normally i would do:

_Mapper.Map<ParentDto,Parent>(dto, local)

but obviously that will change the entire tree and populate the local object with an empty child list. Massively simplifying but would something like

_Mapper.Map<ParentDto, Parent>(dto, local).Ignore(p => p.Children)

be possible?

I should also add I am using SimpleInjector DI framework. So perhaps there is a way to register 2 configurations, one with ignore and one without?

Upvotes: 1

Views: 1810

Answers (2)

Ariwibawa
Ariwibawa

Reputation: 667

For those who still struggle to find this. You can use Autommapper Conditional Mapping.

You can do it like this, in the Initialize

config.CreateMap<ChildDto, ChildDto>().ForMember(dest => dest.Children, opt => opt.Condition(source => source.TriggerChildMap));

This will ignore mapping based on the property in source object. To map against existing destination you need to use Mapper.Map(source, destination) method and not the var result = Mapper.Map<ChildDto>(source) property.

Upvotes: 0

Thanh Nguyen
Thanh Nguyen

Reputation: 712

Use .ForMember(dest => dest.A, opt => opt.MapFrom(src => src.B)) for mapping only properties you need to update.

Upvotes: 2

Related Questions