5

Background: I'm working on a webservice that I want to allow input that has a null field to mean, "don't do an update". The input object is very similar but not identical to the database model, so we're using automapper to do the transforms.

So in the case of an update, I'd like to be able to take the existing values, use them to override any of the null fields in the input, and then save that to do the whole update. So is there a way to make automapper only put values into the destination if the destination field is null?

Seneca
  • 212
  • 2
  • 9
  • It seems that you can do this now. If you're still interested then take a look at [this answer](http://stackoverflow.com/a/16073984/1505426) - I believe its similar to your question. – Mightymuke May 03 '13 at 03:36
  • Possible duplicate of [How to ignore null values for all source members during mapping in Automapper 6?](https://stackoverflow.com/questions/43947475/how-to-ignore-null-values-for-all-source-members-during-mapping-in-automapper-6) – Michael Freidgeim Apr 10 '18 at 13:17

2 Answers2

2

Yes, it can, but you probably wouldn't want to go through the hassle. To do this, you're going to need to have a custom map handler for every field on the object that you want to do this (You may be able to share the custom handler among properties of the same type, but I'm not 100% sure without looking at some of my old code).

Charles Boyung
  • 2,464
  • 1
  • 21
  • 31
  • It does look though that it is possible to do the reverse (ignore null in source). Not sure how to set the ignore condition and still use custom mapping for the parts that need it though. – Seneca Dec 21 '10 at 21:34
  • OK, but how do you even do that for *one field* ? – Faust Jun 27 '14 at 12:16
  • @Faust - Plenty of resources on creating custom mapping logic, such as http://cpratt.co/using-automapper-creating-mappings/ – Charles Boyung Jun 27 '14 at 13:35
-1

I recently solved this on my own problem using a PreCondition with Automapper 5.2.0.

CreateMap<Foo, Foo>()
  .ForAllMembers(opt => opt.Precondition(
    new Func<Foo, bool>( foo =>
      if (opt.DestinationMember == null) return true;
      return false;
    )
  ));

This looks at all destination members, and first looks to see if the destination member is null before even looking at the source member. (If it is not null, then it never looks at the source.)

fkantner
  • 79
  • 5