A. Hasemeyer
A. Hasemeyer

Reputation: 1734

AutoMapper, Don't Overwrite Existing Value if Not Present

I have two models that are similar but not exactly the same

public class ResponseModel
{
    public int? AccountId { get; set; }
    public string AccountNumber { get; set; }
    public string AccountLegalname { get; set; }
    public string Link { get; set; }
}

and

public class Information
{
    public int? IdentityId { get; set; }
    public int? AccountId { get; set; }
    public string AccountNumber { get; set; }
    public string AccountLegalName { get; set; }
}

And I am trying to combine these two models like so

var test1 = new Information(){
    IdentityId = 1234
};

var test2 = new ResponseModel()
{
    AccountId = 123214,
    AccountLegalname = "test",
    AccountNumber = "9239235",
    Link = "link"
};

test1 = _mapper.Map<ResponseModel, Information>(test2);

What I want is this to result in test1 combining the two models values to populate one full instance of Information.

But what actually happens is that all of the information from test2 is inserted into test1 and test1.IdentityId = null

I tried this,

this.CreateMap<ResponseModel, Information>()
    .ForAllMembers(o => o.Condition((source, destination, member) => member != null));

But no luck.

How can I make it so test2 does not override data that exists int test1 and not in test2?

Upvotes: 1

Views: 2349

Answers (1)

Stefan
Stefan

Reputation: 17658

If I am not mistaken you can pass the destination as argument to call that specific functionality through the overload:

test1 = _mapper.Map(test2, test1 );

Upvotes: 3

Related Questions