c# - AutoMapper - 将字符串转换为枚举

标签 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 的枚举中找不到的情况?我试过这个,发现我在转换时收到错误:

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

关于c# - AutoMapper - 将字符串转换为枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48910024/

相关文章:

Automapper 的条件被忽略

c# - 全局异常过滤器或 Application_Error 都没有捕获未处理的异常

c# - 在面板 winform 中放置标签

c# - .NET Framework 和 CLR 版本有什么区别

c# - 当在表单上的某处单击按钮时,wpf 编辑列表框中的项目

c# - TFS 2010 API - 在 workspace.Merge() 状态为 NoActionNeeded 之后

c# - Automapper、MapFrom 和 EF 动态代理

c# - AutoMapper AutoMapper.AutoMapperMappingException : Error mapping types

c# - Entity Framework 和 Automapper 中的数据投影

c# - 从应用程序创建 Sqlite 嵌入式数据库