具有未知值的无效枚举的自动驾驶器
我在源侧有一个无效的枚举属性,并以值0而不是null获取此属性。 但是0不是枚举中的代表值,因此使用ContractingEnumpapping
引发了无法映射枚举的异常。有没有办法将其映射到null
时,每当该值在源枚举中没有表示时?阻止此运行时错误的某种方法?
public class SomeSourceDto
{
public SomeSourceEnum? SomeEnum { get; set; }
}
public class SomeDestinationDto
{
public SomeDestinationEnum? SomeEnum { get; set; }
}
public enum SomeSourceEnum
{
First = 1
}
public enum SomeDestinationEnum
{
First = 1
}
映射配置:
CreateMap<SomeSourceDto, SomeDestinationDto>();
CreateMap<SomeSourceEnum, SomeDestinationEnum>().ConvertUsingEnumMapping(opt => opt.MapByName());
映射:
var someSourceDto = new SomeSourceDto { SomeEnum = 0 };
Mapper.Map<SomeDestinationDto>(someSourceDto);
异常:
automapper.automappermpappingexception
错误映射类型。
...
目标成员:
someenum
我目前的解决方法是在地图之前应用此方法:
someSourceDto.SomeEnum = someSourceDto.SomeEnum == 0 ? null : someSourceDto.SomeEnum;
有更好的方法吗?当我在地图上制作枚举类型时,我无法使用ContructusEnumpapping
。
问题在于,这可能会发生在每个ENUM属性中,因此我有运行时错误ATM的很大风险,因为我无法控制数据的源端。
I have a nullable enum property on the source side and get this property with value 0 instead of NULL.
But 0 is not a represented value in the enum so AutoMapper with ConvertUsingEnumMapping
throws an exception that the enum can not be mapped. Is there a way to map it to NULL
whenever the value is not represented in the source enum? Some way to prevent this runtime error?
public class SomeSourceDto
{
public SomeSourceEnum? SomeEnum { get; set; }
}
public class SomeDestinationDto
{
public SomeDestinationEnum? SomeEnum { get; set; }
}
public enum SomeSourceEnum
{
First = 1
}
public enum SomeDestinationEnum
{
First = 1
}
Mapping configuration:
CreateMap<SomeSourceDto, SomeDestinationDto>();
CreateMap<SomeSourceEnum, SomeDestinationEnum>().ConvertUsingEnumMapping(opt => opt.MapByName());
Mapping:
var someSourceDto = new SomeSourceDto { SomeEnum = 0 };
Mapper.Map<SomeDestinationDto>(someSourceDto);
Exception:
AutoMapper.AutoMapperMappingException
Error mapping types.
...
Destination Member:
SomeEnum
My current workaround is to apply this before the map:
someSourceDto.SomeEnum = someSourceDto.SomeEnum == 0 ? null : someSourceDto.SomeEnum;
Is there a better way? I can't use ConvertUsingEnumMapping
when I make the enum types in the map nullable.
The problem is that this can happen for every enum property so I'm at big risk of runtime errors atm because I have no control over the source side of the data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以这样处理:
您可以将其重写为扩展方法,以便您可以更轻松地将其用于其他DTO
You can work it around like this:
You can rewrite this to an extension method so you can use it more easily for other DTO's