简体   繁体   中英

AutoMapper AfterMap without Generics

I need to set up an AfterMap for AutoMapper but I'm not using the generic version as I'm creating the maps as needed at run time. If I use the generic version I do this:

Mapper.CreateMap<DALEntity, BLLEntity>()
    .AfterMap((DALEntity dalEntity, BLLEntity bllEntity) =>
        (bllEntity as DomainEntityBase).State = DomainEntityState.Unchanged);

Works fine. The other maps which I don't know until run time I am creating like this:

Type BLLClassType = Type.GetType(BLLClassName);
Type DALClassType = Type.GetType(DALClassName);
Mapper.CreateMap(DALClassType, BLLClassType);

But now I can't set AfterMap . Any suggestions? I just need to set the State property of the bllEntity after AutoMapper has done its bit.

Create custom value resolver:

public class StateResolver : IValueResolver
{
    public ResolutionResult Resolve(ResolutionResult source)
    {
        return source.New(DomainEntityState.Unchanged);
    }
}

Usage:

Type BLLClassType = Type.GetType(BLLClassName);
Type DALClassType = Type.GetType(DALClassName);

Mapper.CreateMap(DALClassType, BLLClassType)
      .ForMember("State", opt => opt.ResolveUsing<StateResolver>());

Does it have to be an AfterMap ? For example, could you use UseValue like this:

Mapper.CreateMap<DALEntity, BLLEntity>()
    .ForMember(dest => dest.State,
               opt => opt.UseValue(DomainEntityState.Unchanged));

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