【发布时间】:2018-02-21 15:47:39
【问题描述】:
我使用 AutoMapper 已经有一段时间了,遇到了一个问题,我需要将一个对象映射到另一个对象(如下所示)。
型号:
public Guid guid { get; set; }
public string Status { get; set; }
使用 DTO 传输:
public Guid guid { get; set; }
public Status Status { get; set; }
枚举将包含:
public enum Status {
Example,
AnotherExample,
PossibleExample
}
我已经设法在模型和 DTO 之间进行转换,但是,转换是否处理通过模型对象传入的字符串在 DTO 内的枚举中找不到的情况?我试过这个,发现我在转换时收到错误:
SomeExample ---> System.ArgumentException: Requested value 'SomeExample' was not found.
at System.Enum.EnumResult.SetFailure(ParseFailureKind failure, String failureMessageID, Object failureMessageFormatArgument)
at System.Enum.TryParseEnum(Type enumType, String value, Boolean ignoreCase, EnumResult& parseResult)
at System.Enum.Parse(Type enumType, String value, Boolean ignoreCase)
at AutoMapper.Mappers.EnumMapper.Map(ResolutionContext context)
at AutoMapper.MappingEngine.Map(ResolutionContext context)
传递错误字符串的示例:
{
"guid": "42c1f9f7-a375-4a65-b883-e6e9717d18fe",
"Status": "SomeExample"
}
如果我使用 Enum.Parse,我会假设如果它无法解析字符串,它会将其默认为枚举中的顶部索引?
编辑:这是用于将字符串转换为枚举的映射
CreateMap<Model, Dto>()
.ForMember(d => d.Status, op => op.MapFrom(o => o.Status));
【问题讨论】:
-
您是如何实现转换的?您是否使用不匹配的字符串对其进行了测试?
-
你应该让那个枚举属性为空吗?
-
@OnkelToob 我已经更新了我原来的问题,以符合您的要求。
标签: c# automapper