3
votes

With AutoMapper, can I override the resolved type for a property? For example, given these classes:

public class Parent
{
    public Child Value { get; set; }
}

public class Child { ... }
public class DerivedChild : Child { ... }

Can I configure AutoMapper to automap the Child Value property with a DerivedChild instance? The hypothetical mapping would look something like this:

map.CreateMap<ChildEntity, DerivedChild>();
map.CreateMap<ParentEntity, Parent>()
   .ForMember(p => p.Value, p => p.UseDestinationType<DerivedChild>());

(I'm projecting from LINQ entities. The closest I could find is using a custom type converter, but it looks like I'd need to override the entire mapping.)

2
Can you show the ParentEntity class? - Yacoub Massad
@YacoubMassad let's assume ParentEntity looks just like Parent (with a ChildEntity Value property), so we can automap it by convention. The actual models are more complicated and use mapping expressions, but not in a way that affects the question. - Pathoschild

2 Answers

1
votes

Here is one way to do it:

map.CreateMap<ChildEntity, DerivedChild>();

map.CreateMap<ParentEntity, Parent>()
    .ForMember(
        x => x.Value,
        opt => opt.ResolveUsing(
            rr => map.Map<DerivedChild>(((ParentEntity)rr.Context.SourceValue).Value)));

ResolveUsing allows to specify custom logic for mapping the value.

The custom logic that is used here is actually calling map.Map to map to DerivedChild.

1
votes

You may re-assign new object manually after mapping:

Mapper.CreateMap<ParentEntity, Parent>()
    .AfterMap((src, dest) => dest.Value =  new DerivedChild(){...});

or even re-map it:

   .AfterMap((src, dest) => dest.Value = Mapper.Map<DerivedChild>(dest.Value));