gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:00:35 32 4
gpt4 key购买 nike

我有以下代码片段。

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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com