簡體   English   中英

AutoMapper - 當源屬性不可用時,將目標屬性設置為 null

[英]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設置為 null?

(我正在使用 AutoMapper 9.0.0)

您可以創建一個映射並明確說明要使用的構造函數。

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

有關更多詳細信息,請查看此答案https://stackoverflow.com/a/2239647/7772646

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM