efischency
efischency

Reputation: 471

AutoMapper - how to ignore null fields on the source, while using AutoMapper.Map - sometimes

So we have a situation, where we are mapping from let's say ThingDto:

public class ThingDto {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Guid? SomeNiceId { get; set; }
}

and of course - the destination station Thing:

public class Thing {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Guid? SomeNiceId { get; set; }
}

With that as our context, here is the situation I am trying to solve: We have the DTO as part of a public "contract" library that any outside solution can use in order to send us data. In most cases, when we want to use AutoMapper to map from the ThingDto to the Thing object, everything is peachy. By default, the values that are null on the ThingDto will "null-out" anything that is not null on the Thing object.

However, we have a situation where we need the null values on the source member (the ThingDto) just not map to the destination Thing object. We can do that with a Condition in the setup, but the issue is that we want to only do that sometimes. Is there a run-time setting that we can put when we are calling AutoMapper.Map<ThingDto, Thing>(thingDto, thing);?

This seems like something that would have been an issue for others as well - but no matter what I do I cannot find anything on it. There should be some sort of way to tell AutoMapper on the fly that we don't want to map nulls, but I am coming up with nothing.

Any help would be greatly appreciated.

Upvotes: 3

Views: 835

Answers (1)

Sangman
Sangman

Reputation: 169

Have you considered setting up multiple AutoMapper profiles for the same types, one that contains the Condition, one that doesn't, and then instantiating the configuration valid at that moment?

See: Create two Automapper maps between the same two object types

It might take a wrapper class to make it more maintainable, but I'd suggest something like this:

public class NormalProfile : Profile
{
    protected override void Configure()
    {
        base.CreateMap<ThingDto, Thing>();
    }
}

public class ProfileWithCondition : Profile
{
    protected override void Configure()
    {
        base.CreateMap<ThingDto, Thing>().ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));
    }
}

And in usage:

// Some code where you want to include NULL mappings would call this
var config = new MapperConfiguration(cfg => cfg.AddProfile<NormalProfile>);
config.CreateMapper.Map<ThingDto, Thing>(thing);

// Code where you don't, would do this
var config = new MapperConfiguration(cfg => cfg.AddProfile<ProfileWithCondition>);
config.CreateMapper.Map<ThingDto, Thing>(thing);

Upvotes: 1

Related Questions