0

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)

atiyar
  • 7,762
  • 6
  • 34
  • 75
  • 1
    this article https://stackoverflow.com/questions/4987872/ignore-mapping-one-property-with-automapper may help you – Krishna Varma Feb 21 '20 at 13:29
  • @KrishnaMuppalla, Thanks, but doesn't work. It throws `Customer needs to have a constructor with 0 args or only optional args. (Parameter 'type')` and I didn't want to have a constructor with 0 args. – atiyar Feb 21 '20 at 13:45
  • @BrightHammer, thanks for the idea. That actually might work for the purpose now. – atiyar Feb 21 '20 at 14:36
  • @atiyar the answer i provided in the comments also required a parameterless constructor unfortunately. Check my answer below for a way that does not. – BrightHammer Feb 21 '20 at 14:40

1 Answers1

1

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