AutoMapper:从 int 到 enum 的自定义转换

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

我有以下课程:

public class StatusSqlModel
{
    public int Id { get; set; }
    
    public string Name { get; set; }
}

public enum UploadStatus
{
    Created,
    InProgress,
    Succeeded,
    Failed,
    Cancelled
}

使用 AutoMapper 库如何将 StatusSqlModel 中的“Id”转换为“UploadStatus”枚举,以便映射结果如下:

1 -> 已创建 2 -> 进行中,3 -> 成功,4 -> 失败,5 -> 取消

谢谢。

c# automapper
1个回答
0
投票

就像@LucianBargaoanu 在评论中已经提到的那样,强烈建议确保枚举本身的原始值与其他地方使用的数字相匹配。因此,我建议稍微更改您的枚举,使其看起来像这样:

public enum UploadStatus
{
    Created = 1,
    InProgress,
    Succeeded,
    Failed,
    Cancelled
}

有了这个,就可以非常简单地创建满足您需求的匹配 AutoMapper:

var config = new MapperConfiguration(cfg => 
{
    cfg.CreateMap<UploadStatus, StatusSqlModel>()
        .ConstructUsing(status => new StatusSqlModel 
        {
            Id = (int)status,
            Name = status.ToString()
        });
});
var mapper = new Mapper(config);

var enums = Enum.GetValues<UploadStatus>();

foreach (var value in enums)
{
    var result = mapper.Map<StatusSqlModel>(value);
    Console.WriteLine(JsonSerializer.Serialize(result));
}

如果您无法采取该路线并且需要根据给定的枚举值完全构建模型,您可以尝试以下代码:

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<UploadStatus, StatusSqlModel>()
        .ConstructUsing((status, _) => status switch
            {
                UploadStatus.Created => new StatusSqlModel { Id = 1, Name = nameof(UploadStatus.Created) },
                UploadStatus.InProgress => new StatusSqlModel { Id = 2, Name = nameof(UploadStatus.InProgress) },
                UploadStatus.Succeeded => new StatusSqlModel { Id = 3, Name = nameof(UploadStatus.Succeeded) },
                UploadStatus.Failed => new StatusSqlModel { Id = 4, Name = nameof(UploadStatus.Failed) },
                UploadStatus.Cancelled => new StatusSqlModel { Id = 5, Name = nameof(UploadStatus.Cancelled) },
                _ => throw new ArgumentOutOfRangeException(status.ToString()),
            });
});
var mapper = new Mapper(config);
© www.soinside.com 2019 - 2024. All rights reserved.