将字符串转换为枚举
我一直在使用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中的枚举中未找到通过Model对象传入的字符串的场景? 我试过这个,发现我在转换时收到一个错误:
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));
您可以指定自己的自定义解析器,并确保它可以安全地处理。
http://automapper.readthedocs.io/en/latest/Custom-type-converters.html
.ForMember(x => x.someEnumValue, opt => opt.ResolveUsing(src =>
{
if (Enum.TryParse(typeof(Status), src.someStringValue, out var parsedResult))
return parsedResult;
return Status.Example;
}))
使用AutoMapper配置文件的完整工作示例:
namespace MyProject.Domain.Mapping
{
public enum Status
{
Unknown,
Example,
AnotherExample,
PossibleExample
}
public class RecordPost
{
public Status Status { get; set; }
}
public class RecordDto
{
public string Status { get; set; }
}
public static class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(cfg =>
{
cfg.AddProfile(new RecordProfile());
});
Mapper.AssertConfigurationIsValid();
}
}
public class RecordProfile : Profile
{
public RecordProfile()
{
CreateMap<RecordPost, RecordDto>()
.ForMember(x => x.Status, opt => opt.MapFrom(src => src.Status.ToString()));
CreateMap<RecordDto, RecordPost>()
.ForMember(x => x.Status, opt => opt.ResolveUsing(src =>
{
if (!Enum.TryParse(typeof(Status), src.Status, out var parsedResult))
return Status.Unknown;
return parsedResult;
}));
}
}
}
链接地址: http://www.djcxy.com/p/37433.html