Automapper behavior differs when mapping lists compared to singe objects
I have two objects:
public class Person1
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Person2
{
public string FIRST_NAME { get; set; }
public string LAST_NAME { get; set; }
public int? Foo { get; set; }
}
The difference between the two is that the destination object has the additional property named Foo. I would like Automapper to use the destination value of Foo when mapping between a list of Person1 to Person2.
When I map individual objects I can achieve this behaviour. However when I map a collection of Person1 to Person2 the value of Foo is set to null, instead of being equal to 1. Please see my unit test below.
[TestMethod]
public void TestUseDestValWhenNotFoundIgnore()
{
Mapper.CreateMap<Person1, Person2>()
.ForMember(dest => dest.FIRST_NAME, opt => opt.MapFrom(src => src.FirstName))
.ForMember(dest => dest.LAST_NAME, opt => opt.MapFrom(src => src.LastName))
.ForMember(dest => dest.Foo, opt =>
{
opt.UseDestinationValue();
});
var personList1 = new List<Person1>();
var personList2 = new List<Person2>();
for (int i = 0; i < 50; i++)
{
personList1.Add(new Person1
{
FirstName = "FirtName",
LastName = "LastName"
});
personList2.Add(new Person2
{
FIRST_NAME = "",
LAST_NAME = "",
Foo = 1
});
}
var sourcePerson = new Person1
{
FirstName = "FirstName",
LastName = "LastName"
};
var destinationPerson = new Person2
{
FIRST_NAME = "",
LAST_NAME = "",
Foo = 1
};
// This works as expected, the assert is successful, Foo = 1
Mapper.Map(sourcePerson, destinationPerson);
Assert.IsTrue(destinationPerson.Foo == 1);
// This assert fails, Foo is null for every property
Mapper.Map(personList1, personList2);
Assert.IsTrue(personList2.All(p => p.Foo == 1));
}
链接地址: http://www.djcxy.com/p/51380.html
上一篇: 随机化列表<T>