将单个对象映射到 AutoMapper 中的列表

Map single object to list in AutoMapper

我有两种:

来源:

public class User
{
    public string City { get; set; } = "";
    public Guid Identifier { get; set; } = Guid.NewGuid();
}

目的地:

public class UserDTO 
{
    public Guid Id { get; set; } = Guid.NewGuid();
    public List<Address> Address { get; set; }
}

public class Address
{
    public string City { get; set; } = "";
}

如何使用 AutoMapper 创建从单个 属性 城市到包含城市 属性 的地址列表的映射?这是我现在的映射:

    public UserMappings()
    {
        CreateMap<User, UserDTO>()
            .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Identifier));
    }

您可以像下面这样在映射时即时创建对象,包括数组和列表:

public UserMappings()
{
   CreateMap<User, UserDTO>()
      .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Identifier))
      .ForMember(dest => dest.Address,
                opt => opt.MapFrom(
                           src => new List<Address> { 
                                  new Address { City = src.City }
                           }));
}