映射列表与单独对象相比,Automapper行为有所不同

我有两个对象:

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; }
}

两者之间的区别在于目标对象具有名为Foo的附加属性。 我希望Automapper在将Person1列表映射到Person2时使用Foo的目标值。

当我映射单个对象时,我可以实现这种行为。 但是,当我将Person1的集合映射到Person2时,Foo的值设置为null,而不是等于1.请参阅下面的单元测试。

    [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/51379.html

上一篇: Automapper behavior differs when mapping lists compared to singe objects

下一篇: How to Convert a list of objects to a string list