AutoMapper - 在源 属性 不可用时将目标 属性 设置为空

AutoMapper - set a destination property to null when source property is not available

我有以下两个对象-

public class Customer
{
    public Customer(string userName, string email)
    {
        this.UserName = userName;
        this.Email = email;
    }

    public string UserName { get; }
    public string Email { get; set; }
}

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

我不想在 Customer 中添加构造函数来仅初始化 Email。我可以创建一个从 CustomerUpdateCustomer 的映射,以便将 UserName 设置为空吗?

(我使用的是 AutoMapper 9.0.0)

您可以创建一个映射并明确说明要使用的构造函数。

CreateMap<CustomerUpdate, Customer>()
.ConstructUsing(s => new Customer(null, s.Email))

有关详细信息,请查看此答案