首页
/ Mapperly 中集合属性重命名的正确使用方式

Mapperly 中集合属性重命名的正确使用方式

2025-06-25 04:51:15作者:廉彬冶Miranda

Mapperly 是一个高效的 .NET 对象映射库,它通过源码生成的方式提供了出色的性能。在使用过程中,开发者可能会遇到需要对集合属性进行重命名映射的情况。本文将详细介绍如何正确配置 Mapperly 来实现这一需求。

常见误区

许多开发者初次使用 Mapperly 时,可能会尝试为集合属性单独创建映射方法并添加 MapPropertyAttribute 属性。例如:

[MapProperty(nameof(Parent.Children), nameof(ParentDto.ChildrenList))]
private static partial ICollection<ChildDto> MapToChildrenList(ICollection<Child> children);

这种做法的误区在于试图为集合类型本身创建映射方法,而不是在父对象的映射方法中指定属性映射关系。实际上,MapPropertyAttribute 应该直接应用于父对象的映射方法上。

正确配置方式

正确的做法是将 MapPropertyAttribute 应用于包含集合属性的父对象映射方法:

[Mapper]
public static partial class Mapper
{
    [MapProperty(nameof(Parent.Children), nameof(ParentDto.ChildrenList))]
    public static partial ParentDto MapToParentDto(Parent parent);
    
    public static partial ChildDto MapToChildDto(Child child);
}

这样配置后,Mapperly 会自动生成包含集合属性映射的代码:

public static partial ParentDto MapToParentDto(Parent parent)
{
    var target = new ParentDto();
    target.GivenName = parent.GivenName;
    target.FamilyName = parent.FamilyName;
    target.ChildrenList = parent.Children.Select(MapToChildDto).ToList();
    return target;
}

工作原理

Mapperly 的源码生成机制会分析映射类中的配置,当检测到 MapPropertyAttribute 时:

  1. 识别源类型和目标类型的属性名称对应关系
  2. 自动生成属性赋值的代码
  3. 对于集合类型,会自动处理元素级别的映射
  4. 确保类型安全性和空值安全性

最佳实践

  1. 对于简单的属性映射,直接依赖 Mapperly 的自动映射功能
  2. 对于需要重命名的属性,在父对象映射方法上使用 MapPropertyAttribute
  3. 对于复杂的集合元素转换,可以单独定义元素映射方法
  4. 保持映射方法的简洁性,避免过度配置

总结

正确理解 Mapperly 的属性映射配置方式对于高效使用该库至关重要。记住 MapPropertyAttribute 应该应用于包含该属性的对象映射方法,而不是集合类型本身的映射方法。这种设计使得配置更加直观,同时也保持了代码的简洁性和可维护性。

登录后查看全文
热门项目推荐