简体   繁体   English

AutoMapper - 将字符串转换为枚举

[英]AutoMapper - converting string to enum

I've been using AutoMapper for a while now, and have come across a problem where I would need to map an object to another (shown below).我已经使用 AutoMapper 一段时间了,但遇到了一个问题,我需要将一个对象映射到另一个对象(如下所示)。

Model:模型:

public Guid guid { get; set; }
public string Status { get; set; }

Which is transferred using the DTO:这是使用 DTO 传输的:

public Guid guid { get; set; }
public Status Status { get; set; }

The enum will contain:枚举将包含:

public enum Status {

    Example,
    AnotherExample,
    PossibleExample

}

I've managed to get the conversion working between the model and DTO, however, does the conversion handle the scenario where the string passed in through the Model object isn't found within the enum within the DTO?我已经设法在模型和 DTO 之间进行转换,但是,转换是否处理了在 DTO 的枚举中找不到通过 Model 对象传入的字符串的情况? I have tried this and found that I received an error whilst converting:我试过这个,发现我在转换时收到一个错误:

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)

Example of an incorrect string being passed through:传递错误字符串的示例:

{
    "guid": "42c1f9f7-a375-4a65-b883-e6e9717d18fe",
    "Status": "SomeExample"
}

If I used Enum.Parse, I'd assume that if it couldn't parse the string, it'd default it to the top index in the enum?如果我使用 Enum.Parse,我会假设如果它无法解析字符串,它会将它默认为枚举中的顶部索引?

EDIT: This is the mapping that have used to convert the string to the enum编辑:这是用于将字符串转换为枚举的映射

CreateMap<Model, Dto>()
               .ForMember(d => d.Status, op => op.MapFrom(o => o.Status));

You can just specify your own custom resolver and be certain that it'll be handled safely.您可以指定您自己的自定义解析器并确保它会被安全处理。

http://automapper.readthedocs.io/en/latest/Custom-type-converters.html 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;
    }))

Full working example using an AutoMapper profile:使用 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;
                }));
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM