AutoMapper unflattening 相同类型的复杂对象

AutoMapper unflattening complex objects of same type

我在映射以下复杂类型时遇到问题:

RequestDTO
{
    int OldUserId;
    string OldUsername;
    int NewUserId;
    string NewUsername;
}

Request
{
    User OldUser;
    User NewUser;
}

User
{
    int UserId;
    string Username;
}

Mapping/flattening RequestRequestDTO 很容易。但是如何展开这个对象呢?

假设您将 类 和字段设置为 public,下面的示例显示了如何在 AutoMapper 中处理此问题。您需要告诉它如何从 dto 重建您的复杂类型。

        Mapper.CreateMap<RequestDTO, Request>()
            .ForMember(request => request.OldUser,
                mappingOption =>
                    mappingOption.MapFrom(dto => new User {UserId = dto.OldUserId, Username = dto.OldUsername}))
            .ForMember(request => request.NewUser,
                opt => opt.MapFrom(dto => new User {UserId = dto.NewUserId, Username = dto.NewUsername}));