简体   繁体   English

禁用 AutoMapper 内置枚举映射器

[英]Disable AutoMapper built-in enum mapper

Is it possible to disable the built-in mapper for enums in AutoMapper, or replace it with one that always throws an exception?是否可以禁用 AutoMapper 中枚举的内置映射器,或者将其替换为总是抛出异常的映射器?

I find the built in mapper to be highly unreliable as it will try it's best to map an input to any enum you give it which increases the risk of introducing, difficult to trace, bugs in your code.我发现内置映射器非常不可靠,因为它会尽力将 map 输入到您提供的任何枚举中,这会增加在代码中引入、难以跟踪的错误的风险。

I'd much rather have it fail with an exception telling me that I'm missing a mapper/converter than have it just work and then several steps down the call stack the code fails because the value isn't right in the current context.我宁愿让它失败,一个异常告诉我我缺少一个映射器/转换器,而不是让它正常工作,然后在调用堆栈中执行几个步骤,代码失败,因为该值在当前上下文中不正确。

From what you write I can think of a few options:从你写的我可以想到几个选择:

  1. If you have an enum property on an object, you can ignore it explicitly by using:如果您在 object 上有一个枚举属性,则可以使用以下命令显式忽略它:

     CreateMap<Foo, Bar>().ForMember(dest => dest.EnumProperty, opt => opt.Ignore());
  2. If you create mappings for the properties you want to map and leave out the enum properties you can use:如果您为想要 map 的属性创建映射并省略您可以使用的枚举属性:

     CreateMap<Foo, Bar>().ForMember(...).ForAllOtherMembers(opt => opt.Ignore())
  3. If you want to replace the mapping between to enum types you can overwrite it with:如果要替换枚举类型之间的映射,可以使用以下内容覆盖它:

     Mapper.CreateMap<EnumSrc,EnumDst>().ConvertUsing(value => { throw new Exception(); });

Based on the comment from Lucian i added the following code to my configuration:根据 Lucian 的评论,我将以下代码添加到我的配置中:

services.AddAutoMapper(config =>
{
  var enumMapper = config.Mappers.Single(m => m is AutoMapper.Mappers.EnumToEnumMapper);
  config.Mappers.Remove(enumMapper);
}, typeof(Startup));

This removes the default EnumToEnum mapper and gives me the exception when no mapping is configured.这将删除默认的 EnumToEnum 映射器,并在未配置映射时给我异常。

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

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