public
Last active

AutoMapper AllowNullCollections Configuration

  • Download Gist
AutoMapperConfigurator.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
namespace NullCollectionIssue
{
using AutoMapper;
 
public class ProfileOne : Profile
{
public override string ProfileName
{
get
{
return "ProfileOne";
}
}
 
protected override void Configure()
{
AllowNullCollections = true;
CreateMap<SourceProfileOne, DestProfileOne>();
}
}
 
public class ProfileTwo : Profile
{
public override string ProfileName
{
get
{
return "ProfileTwo";
}
}
 
protected override void Configure()
{
CreateMap<SourceProfileTwo, DestProfileTwo>();
}
}
 
public static class AutoMapperConfigurator
{
public static void Configure()
{
Mapper.Initialize(x =>
{
x.AddProfile<ProfileOne>();
x.AddProfile<ProfileTwo>();
});
}
}
}
MappingTests.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
namespace NullCollectionIssue
{
using AutoMapper;
 
using NUnit.Framework;
 
[TestFixture]
public class MappingTests
{
[Test]
public void AutoMapper_Configuration_IsValid()
{
AutoMapperConfigurator.Configure();
Mapper.AssertConfigurationIsValid();
}
 
[Test]
public void AutoMapper_ProfileOne_AllowsNullCollections()
{
AutoMapperConfigurator.Configure();
Mapper.AssertConfigurationIsValid();
 
var source = new SourceProfileOne { Stuff = null };
var dest = Mapper.Map<SourceProfileOne, DestProfileOne>(source);
 
Assert.That(dest, Is.Not.Null);
Assert.That(dest.Stuff, Is.Null);
}
 
[Test]
public void AutoMapper_ProfileTwo_DoesntAllowNullCollections()
{
AutoMapperConfigurator.Configure();
Mapper.AssertConfigurationIsValid();
 
var source = new SourceProfileTwo { Stuff = null };
var dest = Mapper.Map<SourceProfileTwo, DestProfileTwo>(source);
 
Assert.That(dest, Is.Not.Null);
Assert.That(dest.Stuff, Is.Not.Null);
Assert.That(dest.Stuff, Is.Empty);
}
}
}
ProfileClasses.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
namespace NullCollectionIssue
{
using System.Collections.Generic;
 
public class SourceProfileOne
{
public ICollection<string> Stuff { get; set; }
}
 
public class DestProfileOne
{
public ICollection<string> Stuff { get; set; }
}
 
public class SourceProfileTwo
{
public ICollection<string> Stuff { get; set; }
}
 
public class DestProfileTwo
{
public ICollection<string> Stuff { get; set; }
}
}

The tests AutoMapper_Configuration_IsValid and AutoMapper_ProfileTwo_DoesntAllowNullCollections pass, but the test AutoMapper_ProfileOne_AllowsNullCollections fails because dest.Stuff is not null.

From the StackOverflow question - this behaviour was because I was calling the static Mapper.CreateMap in the configure method. Changed it to the instance method, and it worked.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.