在 AutoMapper 的 Profile 中,我们可以配置来自源对象类型的属性到目标对象类型的属性之间的映射。有时,在映射之前,我们需要丰富目标对象或源对象中的某些属性的值。这个过程称为对象丰富(object enrichment)。
可以使用 AutoMapper Profile 中的 ForMember 方法,根据需要对源和目标进行属性列表处理。下面是一个示例:
public class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class CustomerDto
{
public int Id { get; set; }
public string FullName { get; set; }
}
public class CustomerProfile : Profile
{
public CustomerProfile()
{
CreateMap()
.ForMember(dest => dest.FullName, opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"));
}
}
在上面的示例中,我们创建了一个名为 CustomerProfile 的 AutoMapper Profile,并使用 CreateMap 方法配置了 Customer 类型对象到 CustomerDto 类型对象之间的映射。对于 FullName 属性,我们使用 ForMember 方法配置了它的值。我们通过 Lambda 表达式和 MapFrom 方法传递了一个委托,为 FullName 属性指定了要执行的操作。
这种方法允许您在映射之前对源和目标对象进行更多的控制和处理,以使映射结果更加准确和可靠。因此,丰富 AutoMapper 的 Profile 中的对象是一个好的实践。
在实际项目中,您可以根据需求对其他属性进行丰富,例如日期格式化、字符串处理和计算等。