我无法尝试使用 AutoMapper 将字符串从 API 解析为枚举

问题描述 投票:0回答:1

我正在尝试使用 AutoMapper 将

TryParse
一个字符串从 API 转换为
Enum
,如果无法解析,他应该返回一个“默认值”。

我的模型是:班级费用

public long Id { get; set; }
public string Description { get; set; }
public double Value { get; set; }
public DateTime Date { get; set; }
public Category Categories { get; set; }

我的 DTO 是:Class ExpenseDTO

public long Id { get; set; }
public string Description { get; set; }
public double Value { get; set; }
public DateTime Date { get; set; }
public string Categories { get; set; }

枚举包含:

public enum Category : int {
   Others = 0,
   Food = 1,
   Health = 2,
   Home = 3,
   Transport = 4,
   Education = 5,
   Chill = 6,
   Unexpected = 7
}

我已经尝试过在 Stack OverFlow 上看到的解决方案,即:

CreateMap<ExpenseDTO, Expense>()
        .ForMember(dest => dest.Category,
            opt =>
            {
                object? parsedResult;
                opt.MapFrom(src =>
                    Enum.TryParse(typeof(Category), src.Categories, true, out parsedResult) ? parsedResult : Category.Others);
            })
        .ReverseMap().ForMember(dest => dest.Category,
            opt => opt.MapFrom(src => src.Categories.ToString()));

当我尝试发送不存在的类别(例如“测试”)时,该解决方案仍然会引发异常。

API 返回该错误:

Mapping types:
ExpenseDTO -> Expense
Challenge.API.ExpenseDTO -> Challenge.Domain.Expense
 
Type Map configuration:
ExpenseDTO -> Expense
Challenge.API.ExpenseDTO -> Challenge.Domain.Expense

有人可以帮助我吗?

c# .net automapper
1个回答
1
投票

如果您需要比简单的 src.Field => dest.Field 类型映射更复杂的东西,您可以使用值解析器来插入自定义逻辑,如下所示:

public class CategoriesEnumValueResolver : IValueResolver<ExpenseDTO, Expense, Category>
{
    public Category Resolve(ExpenseDTO source, Expense destination, Category destMember, ResolutionContext context)
    {
        if (Enum.TryParse<Category>(source.Categories, out var category))
            return category;

        return Category.Others;
    }
}

然后,您可以告诉 AutoMapper 在创建地图时使用该值解析器:

CreateMap<ExpenseDTO, Expense>()
    .ForMember(m => m.Categories, opt => opt.MapFrom<CategoriesEnumValueResolver>());
© www.soinside.com 2019 - 2024. All rights reserved.