与单个对象相比,映射列表时自动映射行为会有所不同

时间:2015-08-20 06:03:35

标签: c# mapping 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));
    }

0 个答案:

没有答案