1

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?

A. Hasemeyer
  • 1,452
  • 1
  • 18
  • 47
  • I remember doing something like this at one point and had to set conditionals for each member. – JSON Jul 30 '19 at 18:43
  • I think Obeds answer in the bottom works: https://stackoverflow.com/questions/12262940/usedestinationvalue-only-when-destination-property-is-not-null – Matt Luccas Phaure Minet Jul 30 '19 at 18:50
  • 1
    The problem here is not that you're overwriting the properties, the problem is that the overload you used constructed a new target object, the instance in `test1` was never used, instead you overwrote `test1` with this new instance, losing the original one where you had assigned to that Id property. – Lasse V. Karlsen Jul 30 '19 at 18:59

1 Answers1

3

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 );
A. Hasemeyer
  • 1,452
  • 1
  • 18
  • 47
Stefan
  • 17,448
  • 11
  • 60
  • 79