c# - Automapper DynamicMap 无法映射匿名类型列表

标签 c# automapper anonymous-types

我有以下代码片段。

var files = query.ToList();
var testFile = Mapper.DynamicMap<EftFileDto>(files.First());
var filesDto = Mapper.DynamicMap<List<EftFileDto>>(files);

testFile 具有正确映射的值,但 filesDto 为空。

似乎 dynamicMap 适用于单个项目,但不适用于列表?

files 是匿名对象的列表。

编辑:如果我使用数组也不起作用。我可以让它工作,但是......

        var filesDto = query.Select(Mapper.DynamicMap<EftFileDto>).ToList();

最佳答案

In most mapping scenarios, we know the type we’re mapping to at compile time. In some cases, the source type isn’t known until runtime, especially in scenarios where I’m using dynamic types or in extensibility scenarios.

The DynamicMap call creates a configuration for the type of the source object passed in to the destination type specified. If the two types have already been mapped, AutoMapper skips this step (as I can call DynamicMap multiple times for this example).

来源:http://lostechies.com/jimmybogard/2009/04/15/automapper-feature-interfaces-and-dynamic-mapping/

较短的版本:DynamicMap 与调用 CreateMap 然后调用 Map 相同。

一些虚拟的 Person 类

public class Person
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }
    }

假设您有一个人员列表。

var persons = new List<Person>();
for (int i = 0; i < 100; i++)
{
      persons.Add(new Person { 
                Name = String.Format("John {0}", i), 
                Surname = String.Format("Smith {0}", i), 
                Age = i });
}

然后您选择添加新属性的人。

var anonymousTypes = persons.Select(p => new { 
            p.Name, 
            p.Surname, 
            FullName = String.Format("{0}, {1}", p.Surname,p.Name) }).ToList();

正确映射第一人称

var testFile = Mapper.DynamicMap<Person>(anonymousTypes.First()); 

要正确映射您将使用的所有人

var testFiles  = anonymousTypes.Select(Mapper.DynamicMap<Person>).ToList(); 

关于c# - Automapper DynamicMap 无法映射匿名类型列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14630473/

相关文章:

c# - 基类中的 Autofac 属性注入(inject)

c# - 使用 Scan 为泛型类型自动注册 StructureMap

AutoMapper 一对多关系

c# - 匿名类型的编译器优化

c# - 没有消息帧的 TCP 上的 Xml

c# - 简单的 ADO.NET C# 存储过程生成器

c# - AutoMapper:映射记录类型问题

c# - 当指定条件 != null 时,Automapper 未正确映射 null 列表成员

c# - 使用 ServiceStack.Text 将 json 字符串反序列化为对象

java - 匿名方法使用泛型值作为参数