简体   繁体   中英

Automapper map an inherited object to a child

I have the following classes:

Source:

public class Source
{
    public int Amount { get; set; }
}

Destination:

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

public class ChildBase
{

}

public class Child : ChildBase
{
    public int Amount { get; set; }
}

For the map I'm trying to create, I want to map from Source to Parent . The property on the Parent is defined as ChildBase but I want the map to actually map to Child . How can I get the mapper to map to Child ?

I have a simple map defined as:

CreateMap<Source, Parent>()
  .ForMember(d => d.Child, opt => opt.MapFrom(s => s));

CreateMap<Source, Child>();

But obviously this is trying to look for a map with the destination of ChildBase . I tried casting the destination to be Child but that didn't work.

Any ideas?

You need to use the custom ValueResolver in AutoMapper.

Mapper.CreateMap<Source, Parent>()
    .ForMember(p => p.Child, o => o.ResolveUsing(s => new Child { Amount = s.Amount }));

If you want to re-use this logic, you can put the code into a class instead of a lambda expression.

class SourceToChildValueResolver : ValueResolver<Source, Child>
{
    protected override Child ResolveCore(Source source)
    {
        return new Child { Amount = source.Amount };
    }
}

//register the resolver
CreateMap<Source, Parent>()
    .ForMember(p => p.Child, o => o.ResolveUsing<SourceToChildValueResolver>());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM