AutoMapper failing to map a simple list

谁都会走 提交于 2019-12-08 05:57:23

问题


I have used automapper for mapping lists in the past, for for some reason it won't work in this case.

     public class MyType1 {
            public int Id { get; set; }
            public string Description { get; set; }
        }


        public class MyType2 {
            public int Id { get; set; }
            public string Description { get; set; }
        }

     public void DoTheMap() {
                Mapper.CreateMap<MyType2, MyType1>();
                Mapper.AssertConfigurationIsValid();

                var theDto1 = new MyType2() { Id = 1, Description = "desc" };
                var theDto2 = new MyType2() { Id = 2, Description = "desc2" };
                List<MyType2> type2List = new List<MyType2> { theDto1, theDto2 };

                List<MyType1> type1List = Mapper.DynamicMap<List<MyType1>>(type2List);
    //FAILURE.  NO EXCEPTION, BUT ZERO VALUES

                List<MyType1> type1List2 =type2List.Select(Mapper.DynamicMap<MyType1>).ToList();
   //SUCCESS, WITH LINQ SELECT
        }

回答1:


Change this:

Mapper.DynamicMap<List<MyType1>>(type2List)

To this:

Mapper.Map<List<MyType1>, List<MyType2>>(type2List);

DynamicMap is only if you don't know the type at compile time - for things like anonymous types.



来源:https://stackoverflow.com/questions/5975240/automapper-failing-to-map-a-simple-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!