使用LinqToExcel映射/转换以处理枚举模型

本文关键字:处理 枚举 模型 转换 LinqToExcel 映射 使用 | 更新日期: 2023-09-27 18:01:13

我在处理试图导入数据库的Excel文件的一列时遇到问题。该属性引用枚举模型。我尝试放置整数值(指Enum索引(或字符串值本身,但显然不起作用。

我应该如何使用(我假设(AddTransformation方法来处理这个问题?

使用LinqToExcel映射/转换以处理枚举模型

我能够通过将单元格的值映射到转换函数中的枚举值来实现这一点:

excel.AddTransformation<DataImportJob>(x => x.Status, cellValue =>
{
    switch (cellValue)
    {
        case "Failed":
            return JobStatusType.Failed;
        case "InProgress":
            return JobStatusType.InProgress;
        case "Scheduled":
            return JobStatusType.Scheduled;
        case "Success":
            return JobStatusType.Success;
        default:
            return JobStatusType.Undefined;
    }
});

是的,试试AddTransformation方法,看看它是否有效。

解决方案是创建一个新对象并手动映射属性。Enum是这样处理的:

MyEnumProperty = (MyEnumProperty)Convert.ToInt32(c["ColumnNameInExcel"])

我尝试了具有从Double到enum的Invalid强制转换问题的AddTransformation方法。

excelFile.AddTransformation<Table>(x => x.Company, cellValue => (MyEnumProperty)Convert.ToInt32(cellValue));