7

I want to use AutoMapper with proto3, but the biggest problem I have is in mapping from a source property that may allow null into a proto that never does. When doing such population manually, one must do something like this:

var proto = new Proto();

if (source.Field != null)
{
    proto.Field = source.Field;
}

I still find it absurd, but that's apparently how it is with proto3.

Anyway, this means that mappings must have conditions on them to ensure null values do not propagate to the proto:

config
    .CreateMap<Source, Proto>()
    .ForMember(
        x => x.Field,
        options => options.Condition(source => source.Field != null));

I can feel this getting old really fast as I have a lot of properties in my protos.

What I'm wondering is whether there a way for me to handle this at a higher level of abstraction?

me--
  • 1,978
  • 1
  • 22
  • 42
  • 1
    This might help? https://github.com/AutoMapper/AutoMapper/issues/1703#issuecomment-250137782 if it does I will post as answer – Ramesh Feb 13 '19 at 04:21
  • I'm going with this for now, which seems like a simpler way than what's in your link: `.ForAllMembers(options => options.Condition((_, __, sourceMember) => sourceMember != null))` – me-- Feb 13 '19 at 05:30
  • Yes, because that solution covers value types too, and I'm guessing you don't need that. – Lucian Bargaoanu Feb 13 '19 at 05:47

1 Answers1

7

You can use ForAllOtherMembers method on the CreateMap<Source,Proto> output and specify the condition. This will address your problem of not specifying for each property

Sample code

config
    .CreateMap<Source, Proto>()
    .ForAllOtherMembers(
        options => options.Condition((src, dest, srcValue) => srcValue != null));
Ramesh
  • 13,043
  • 3
  • 52
  • 88