MapsterMapper / Mapster

A fast, fun and stimulating object to object Mapper
MIT License
4.29k stars 327 forks source link

map List<interface> to List<object> cant work well #588

Closed solapvk closed 1 year ago

solapvk commented 1 year ago

i have a test like this:

    public interface ITest
    {
    }

    public class Test : ITest
    {
        public int? Id { get; set; }
    }

    public class TestB
    {
        public int? Id { get; set; }
    }
        public void MapInterfaceToObject()
        {
            var test = new Test();
            test.Id = 10;

            TestB? testB = mapper.Map<TestB>((ITest)test);
            TestB? testc = mapper.Map<TestB>((object)test);

            Assert.Equal(10, testB.Id);//success
            Assert.Equal(10, testc.Id);//success

            List<object> list1 = new List<object>();
            list1.Add(test);
            list1.Add(testc);
            var lis1 = mapper.Map<List<TestB>>(list1);

            Assert.Equal(10, lis1[0].Id);//success
            Assert.Equal(10, lis1[1].Id);//success

            List<ITest> list = new List<ITest>();
            list.Add(test);
            var lis = mapper.Map<List<TestB>>(list);

            Assert.Equal(10, lis[0].Id);//here test fail,  actually Id=null

            Dictionary<string, ITest> dic = new Dictionary<string, ITest>();
            dic.Add("1", test);
            var d2 = mapper.Map<Dictionary<string, TestB>>(dic);

            Assert.Equal(10, d2["1"].Id);//here test fail,  actually Id=null
        }

Is this a bug or a feature? Do we need to configure so that the List<interface> can be mapped like List<object>?

andrerav commented 1 year ago

I'm not sure how you expect this to work. Please use MapWith() to map this correctly.