如何结合条件语句使用AutoMapper优化Excel数据导入的实体赋值代码
实现步骤
1. 安装依赖
首先通过NuGet安装AutoMapper相关包:
- 基础包:
AutoMapper - ASP.NET Core项目额外安装:
AutoMapper.Extensions.Microsoft.DependencyInjection
2. 配置映射规则
创建自定义映射配置类,继承AutoMapper的Profile类,把字段转换逻辑统一写在映射规则里:
using AutoMapper; using System.Data; public class ExcelMappingProfile : Profile { public ExcelMappingProfile() { // 源类型为你使用的Excel reader类型,这里以IDataReader为例 CreateMap<IDataReader, ExcelFileModel>() // Section字段转换逻辑和原有逻辑完全一致 .ForMember(dest => dest.Section, opt => opt.MapFrom(src => decimal.TryParse(src.GetValue(2)?.ToString()?.Trim(), out decimal _section) ? _section : null)) .ForMember(dest => dest.CourseNumber, opt => opt.MapFrom(src => src.GetValue(3)?.ToString()?.Trim())) .ForMember(dest => dest.Department, opt => opt.MapFrom(src => src.GetValue(4)?.ToString()?.Trim())); } }
如果你使用的是EPPlus等其他Excel读取库,只需要把CreateMap的源类型替换为对应行对象的类型即可,映射逻辑保持一致。
3. 注册AutoMapper服务(ASP.NET Core场景)
在项目启动配置文件(Program.cs)中注册AutoMapper,自动扫描刚才写的映射规则:
builder.Services.AddAutoMapper(typeof(ExcelMappingProfile));
4. 改造原有业务代码
注入IMapper后直接替换原有手动赋值逻辑即可:
public class YourBusinessService { private readonly IMapper _mapper; // 构造函数注入IMapper实例 public YourBusinessService(IMapper mapper) { _mapper = mapper; } public List<ExcelFileModel> ProcessExcelFileData(IFormFile file) { var excelData = new List<ExcelFileModel>(); // 原有Excel文件读取、reader初始化逻辑保持不变 while (reader.Read()) { counter++; // 一行代码完成字段转换和赋值 excelData.Add(_mapper.Map<ExcelFileModel>(reader)); } return excelData.Any() ? excelData : new List<ExcelFileModel>(); } }
优化建议
- 可以把列索引定义为常量,比如
public const int SectionColumnIndex = 2,后续Excel列结构调整时只需要修改常量值,无需修改映射逻辑。 - 所有字段转换逻辑都可以统一放到映射配置中维护,业务代码会更简洁。
内容的提问来源于stack exchange,提问作者Happy
相关产品推荐
相关产品推荐

