简体   繁体   中英

Custom AutoMapper name/type convention for all mappings?

I'm using AutoMapper 6.0 in my ASP.NET MVC application for mapping between entities and view models. Entities are using byte[8] Version property, but view models are using ulong Version property. Because of different property types default mapping ignores that field and I'm ending up with default value for view model (that is 0).

Currently I'm calling below code after each _mapper.Map(entity,viewModel);

_mapper.Map(entity,viewModel);
viewModel.Version = System.BitConverter.ToUInt64(entity.Version.ToArray(), 0);

How can I configure AutoMapper during initialisation so second line won't be necessary?

I have hundreds of models so instead of creating custom maps with ForMember(cfg) configuration I would like to amend AutoMapper convention so above type of conversion happens by default for each map, eg:

public class MyCustomProfile : AutoMapper.Profile
{
    public MyCustomProfile()
    {
        CreateMissingTypeMaps = true;
        //use custom converter for this convetion: ulong vVersion = BitConverter.ToUInt64(eVersion.ToArray(), 0);
    }
}

You could try a type mapping with the ConvertUsing:

CreateMap<byte, ulong>().ConvertUsing(System.Convert.ToUInt64);

Edit, as requested:

CreateMap<byte[], ulong>().ConvertUsing(x=> BitConverter.ToUInt64(x, 0));

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