c# Automapper 将字符串映射到嵌套对象中数组的第一个元素

c# Automapper mapping string to 1st element of array in nested object

我的存储库正在返回一个具有此定义的用户对象,其中用户将永远只有 1 个电子邮件地址。

用户

    public class User
{
    [Key]
    public string UserName { get; set; }

    [Required]
    [MaxLength(50)]
    public string DisplayName { get; set; }

    [Required]
    [MaxLength(50)]
    public string  Email { get; set; }

}

然后我将其映射到一个 UserDTO 对象,以便传输到他们期望电子邮件字段是电子邮件对象数组的环境。所以我根据接收系统的需要创建了这个电子邮件对象,如下所示。我们可以将 Type 设置为值为 "work" 的字符串,将 Primary 设置为布尔值 true;

    public class Email
{
    public string Value { get; set; }

    public string Type { get; set; }

    public bool Primary { get; set; }
}

然后我的 UserDTO 看起来像这样:

    public class UserReadDto
{

    public string schemas { get; set; } 

    public string UserName { get; set; }

    public string externalId { get; set; }

    // this should be an array of names, this is a name object. 
    public Name name { get; set; }

    public string DisplayName { get; set; }

    public Email[] Emails { get; set; }
}

是否可以让 Automapper 将电子邮件字符串(例如 test@test.com)映射到其中只有一个电子邮件对象作为目标的电子邮件对象数组?

您可以为您创建一个 returns 列表的函数,如下所示:

public static Email[] GetList(User x)
{
    return new List<Email>
    {
        new Email()
        {
            Value = x.Address
        }
    }.ToArray()
}

然后你可以把这个放在你的映射配置中:

var configuration = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<User, UserReadDto>()
       .ForMember(d => d.Emails, src =>
       {
           src.MapFrom(x => GetList(x));
       });
});

您可以将 GetList() 方法放在您的 User 模型中,或者其他任何地方,只要您可以在您的映射配置中访问它。

有关自动映射器文档页面的更多信息 here