komsky
komsky

Reputation: 1588

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);
    }
}

Upvotes: 1

Views: 435

Answers (1)

sleeyuen
sleeyuen

Reputation: 951

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));

Upvotes: 2

Related Questions