Automapper: Handling NULL members

A question about null members came up on the Automapper mailing list.  While the problem wasn’t with Automapper, investigating the issue led to an interesting feature in Automapper.

Normally, Automapper ignores null members.  After all, what is there really to do?  Imagine these source classes:

public class Source
{
    public int Data { get; set; }
    public Address Address { get; set; }
}
 
public class Destination
{
    public string Data { get; set; }
    public Address Address { get; set; }
}
 
public class Address
{
    public string AddressType { get; set; }
    public string Location { get; set; }
}

And imagine a simple mapping example with these classes:

Mapper.CreateMap<Source, Destination>();
 
var source = new Source
                {
                    Data = 22,
                    Address = new Address
                                {
                                    AddressType = "Home",
                                    Location = "Michigan",
                                },
                };
 
var dest = Mapper.Map<Source, Destination>(source);

The variable ‘dest’ would have a complete mapping of the Data member and the Address member.

But what if the source had no address?

Mapper.CreateMap<Source, Destination>();
 
var source = new Source
{
    Data = 22,
};
 
var dest = Mapper.Map<Source, Destination>(source);

In that case, Automapper would just leave the Destination.Address member null as well.  But what if we always wanted an Address defined – even if it’s just got some default data?  Use the “NullSubstitute” option:

Mapper.CreateMap<Source, Destination>()
    .ForMember(d => d.Address, o => o.NullSubstitute(new Address
                                                         {
                                                             AddressType = "Unknown",
                                                             Location = "Unknown",
                                                         }));
 
var source = new Source
{
    Data = 22,
};
 
var dest = Mapper.Map<Source, Destination>(source);

Now, the ‘dest’ variable will have an Address defined with a type and location of “Unknown”.  Very handy!

Technorati Tags: ,,

No Comments