atiyar
atiyar

Reputation: 8305

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

I have the following two objects -

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; }
}

I don't want to add a constructor in Customer to initialize Email only. Can I create a map from CustomerUpdate to Customer so that UserName is set to null?

(I'm using AutoMapper 9.0.0)

Upvotes: 0

Views: 479

Answers (1)

BrightHammer
BrightHammer

Reputation: 103

You can create a map and explicitly state the constructor to use.

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

For more details check this answer https://stackoverflow.com/a/2239647/7772646

Upvotes: 1

Related Questions