Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper sets an array property to a zero-length array rather than null

Tags:

automapper

I'm using Automapper to copy values from one instance to another, and I'm finding that if the class has an array property, and the source instance has the property set to null, Automapper sets the destination property to a zero-length array instead of null as I expected.

Is there a way to configure Automapper to set the destination to null when the source is null?

In case my explanation is unclear, the following code illustrates what I'm trying to describe:

public class Test {     public byte[] ByteArray { get; set; }     public int? NullableInt { get; set; }     public int Int { get; set; } }  class Program {     static void Main(string[] args)     {         Mapper.CreateMap<Test, Test>();          var test1 = new Test { Int = 123, NullableInt = null, ByteArray = null };         var test2 = Mapper.Map<Test>(test1);          // test1:  Int == 123, NullableInt == null, ByteArray == null         // test2:  Int == 123, NullableInt == null, ByteArray == byte[0]  <-- expect this to be null     } } 
like image 449
Jeff Ogata Avatar asked Dec 06 '11 23:12

Jeff Ogata


People also ask

Does AutoMapper handle null?

The Null substitution allows us to supply an alternate value for a destination member if the source value is null. That means instead of mapping the null value from the source object, it will map from the value we supply.

What is the use of AutoMapper in C#?

AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.

Is AutoMapper case sensitive?

The name should be the same but NOT CASE-SENSITIVE i.e. the name in source object can be “id” and that in the target object can be “ID”.


1 Answers

I found that this was already reported as an issue, and a new configuration option was added (see this commit). At this time, the option is not in the release available via NuGet, but I was able to figure out a way to handle this until the next version is released:

Mapper.CreateMap<Test, Test>()     .ForMember(t => t.ByteArray, opt => opt.ResolveUsing(t => t.ByteArray == null ? null : t.ByteArray)); 

Update:

As of version 2.1.265.0, you can using the AllowNullCollections property:

Mapper.Configuration.AllowNullCollections = true; Mapper.CreateMap<Test, Test>(); 
like image 82
Jeff Ogata Avatar answered Oct 08 '22 12:10

Jeff Ogata