Skip to content

@mightymuke /AutoMapperConfigurator.cs
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
AutoMapper AllowNullCollections Configuration
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>();
});
}
}
}
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);
}
}
}
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; }
}
}
@mightymuke
Owner

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

@mightymuke
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.