【问题标题】:c# Automapper mapping string to 1st element of array in nested objectc# Automapper 将字符串映射到嵌套对象中数组的第一个元素
【发布时间】:2020-05-08 23:06:24
【问题描述】:

我的存储库正在返回一个用户对象,该对象具有此定义,其中用户将永远只有 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 设置为 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 将电子邮件字符串(例如 test@test.com)映射到一个电子邮件对象数组,其中只有一个电子邮件对象用于目的地?

【问题讨论】:

  • 没有 AM 怎么办?

标签: c# automapper


【解决方案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 模型中,或者任何其他地方,只要您可以在映射配置中访问它。

更多信息请参见 automapper here 的文档页面。

【讨论】:

    猜你喜欢
    • 2021-09-12
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 2022-01-06
    • 2019-04-26
    • 1970-01-01
    相关资源
    最近更新 更多