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).

Model:

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

Which is transferred using the 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? 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?

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

.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:

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/37434.html

上一篇: 什么是保持多语言数据的最佳数据库结构?

下一篇: 将字符串转换为枚举