AutoMapper无法映射简单列表 [英] AutoMapper failing to map a simple list

查看:155
本文介绍了AutoMapper无法映射简单列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我过去曾经使用automapper映射列表,由于某种原因,在这种情况下它不起作用.

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
        }

推荐答案

更改此内容:

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

对此:

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

仅当您在编译时不知道类型时,DynamicMap才适用-匿名类型之类的东西.

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

这篇关于AutoMapper无法映射简单列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆