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

问题描述 投票:0回答:1

我的存储库正在返回一个具有此定义的用户对象,其中该用户将永远只有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对象,以传输到他们希望Email字段为Email对象数组的环境。因此,我根据接收系统的需要创建了这个Email对象,如下所示。我们可以将Type设置为一个值为“ work”的字符串,并将Primary设置为boolean 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将电子邮件字符串(例如[email protected])映射到仅包含一个电子邮件对象作为目的地的电子邮件对象数组?

c# automapper
1个回答
1
投票

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

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的文档页面上的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.