简体   繁体   English

所有映射的自定义AutoMapper名称/类型约定?

[英]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. 我在ASP.NET MVC应用程序中使用AutoMapper 6.0在实体和视图模型之间进行映射。 Entities are using byte[8] Version property, but view models are using ulong Version property. 实体使用byte [8] Version属性,但是视图模型使用ulong Version属性。 Because of different property types default mapping ignores that field and I'm ending up with default value for view model (that is 0). 由于属性类型不同,默认映射将忽略该字段,而我最终得到视图模型的默认值(即0)。

Currently I'm calling below code after each _mapper.Map(entity,viewModel); 目前,我在每个_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? 如何在初始化期间配置AutoMapper,这样就不需要第二行了?

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: 我有数百种模型,所以我不想修改ForMmber(cfg)配置的自定义地图,而是要修改AutoMapper约定,因此默认情况下,每种地图的转换类型都会发生,例如:

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: 您可以尝试使用ConvertUsing进行类型映射:

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

Edit, as requested: 根据要求编辑:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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