AutoMapper - 将字符串转换为枚举

时间:2018-02-21 15:47:40

标签: c# automapper

我一直在使用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));

1 个答案:

答案 0 :(得分:0)

您可以指定自己的自定义解析程序,并确保它可以安全处理。

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;
                }));
        }
    }
}