简体   繁体   中英

Automapper mapping sub items

I am trying to use Automapper to map from a frontend object hierarchy to a backend object hierarchy. This necessitates creating a subcomponent on the fly from several sources in the source object. I've done this in other places with no trouble. But in the case, the newly created object requires its own properties to also be mapped.

I've added a generic version of what I am talking about below.

config.CreateMap<BusinessObject, WebObject>()
    .ForMember(d => d.Component, opts => opts.ResolveUsing(b =>
    {
        return new ComponentBusinessObject()
        {
            Date = b.Property1.Date,
            Definition = b.Property2.Definition  // This needs converting from (DefinitionWebObject to DefinitionBusinessObject)
        };
    }));

Does anyone know a way of re-invoking the mapper at the lower level? ('Definition' in the example above.)

Building off of GTG's comment:

If you map DefinitionWebObject and DefinitionBusinessObject together prior to your BusinessObject and WebObject mapping, you should be able to call Mapper.Map inside your parent map.

config.CreateMap<DefinitionWebObject, DefinitionBusinessObject>();  // Create sub-mapping first.

config.CreateMap<BusinessObject, WebObject>()
    .ForMember(d => d.Component, opts => opts.ResolveUsing(b =>
    {
        return new ComponentBusinessObject()
        {
            Date = b.Property1.Date,
            Definition = Mapper.Map<DefinitionBusinessObject>(b.Property2.Definition)
        };
    }));

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