Automapper: Handling NULL members

Posted by PSteele on ASP.net Weblogs See other posts from ASP.net Weblogs or by PSteele
Published on Fri, 18 Mar 2011 16:53:21 GMT Indexed on 2011/03/19 0:11 UTC
Read the original article Hit count: 627

Filed under:
|

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: ,,

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about automapper