AutoMapper中IValueResolver如何获取待映射目标属性名实现多属性复用
实现方案
1. 修正映射配置
同一个<AlertLine, AlertLineDto>的映射规则不需要重复声明CreateMap,直接链式调用ForMember配置多个属性即可:
CreateMap<AlertLine, AlertLineDto>() .ForMember(dest => dest.BusinessArea, opt => opt.MapFrom<MyResolver>()) .ForMember(dest => dest.Division, opt => opt.MapFrom<MyResolver>()) .ForMember(dest => dest.SubDivision, opt => opt.MapFrom<MyResolver>());
2. 改造Resolver复用逻辑
IValueResolver的Resolve方法第三个入参destMember就是当前正在映射的目标属性名称,直接使用即可。你可以预先建立目标属性名和AddlInformation中对应ID字段、查询逻辑的匹配规则,即可实现同一份逻辑适配多个属性:
public class MyResolver : IValueResolver<AlertLine, AlertLineDto, string> { private readonly ICatalogService _catalogService; // 修正构造函数名和类名保持一致,原代码此处为笔误 public MyResolver(ICatalogService catalogService) { _catalogService = catalogService; } public string Resolve(AlertLine source, AlertLineDto destination, string destMember, ResolutionContext context) { var variant = JsonSerializer.Deserialize<AddlInformation>(source.AddlDimension); // 可根据实际业务调整匹配规则,这里示例不同属性对应不同的ID字段和查询接口 var propertyMap = new Dictionary<string, (int Id, Func<int, object> Query)> { { "BusinessArea", (variant.BUSINESS_AREA_ID, _catalogService.GetCachedBusinessAreaById) }, { "Division", (variant.DIVISION_ID, _catalogService.GetCachedDivisionById) }, { "SubDivision", (variant.SUB_DIVISION_ID, _catalogService.GetCachedSubDivisionById) } }; if (!propertyMap.TryGetValue(destMember, out var config) || config.Id <= 0) { return string.Empty; } var data = config.Query(config.Id); // 所有查询结果统一取Description字段,符合你提到的处理逻辑完全一致的要求 return data?.GetType().GetProperty("Description")?.GetValue(data)?.ToString() ?? string.Empty; } }
可选优化
如果不想用反射读取Description属性,可以给所有目录实体添加统一的IHasDescription接口,所有实体实现该接口后即可强类型读取属性,性能更优。
内容的提问来源于stack exchange,提问作者pedrommuller
相关产品推荐
相关产品推荐

