I have a mapping of a class MyClass
to the same class MyClass
.
The class has a List<T>
property in it. The List<T>
is NULL before the map.
After the mapped with AutoMapper , the List<T>
is not NULL anymore. ( AllowNullDestinationValues
does nothing here ...)
Is this intentional or a bug ? Am I missing some configuration step ?
using System.Collections.Generic;
using System.Diagnostics;
using AutoMapper;
namespace ConsoleApplication1
{
public class MyClass
{
public string Label { get; set; }
public List<int> Numbers { get; set; }
}
class Program
{
static void Main(string[] args)
{
Mapper.CreateMap<MyClass, MyClass>();
MyClass obj1 = new MyClass { Label = "AutoMapper Test" };
MyClass obj2 = new MyClass();
Mapper.Map(obj1, obj2);
Debug.Assert(obj2 != null && obj2.Numbers == null, "FAILED");
}
}
}
I use the AutoMapper v4.1.1 from NuGet.
By default, AutoMapper will map a null collection to an empty collection instead. You can modify this by creating your own AutoMapper profile for configuration.
Take a look at the code below.
public class MyClass
{
public string Label { get; set; }
public List<int> Numbers { get; set; }
}
class Program
{
static void Main(string[] args)
{
Mapper.AddProfile<MyProfile>(); // add the profile
MyClass obj1 = new MyClass { Label = "AutoMapper Test" };
MyClass obj2 = new MyClass();
Mapper.Map(obj1, obj2);
Debug.Assert(obj2 != null && obj2.Numbers == null, "FAILED");
}
}
public class MyProfile : Profile
{
protected override void Configure()
{
AllowNullCollections = true;
CreateMap<MyClass, MyClass>();
// add other maps here.
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.