【问题标题】:Automapper: map an anonymous/dynamic typeAutomapper:映射匿名/动态类型
【发布时间】:2026-01-26 21:25:01
【问题描述】:

我需要一些帮助来使用 Automapper 映射匿名对象。目标是在 ProductDto 中结合 Product 和 Unity(其中 unity 是产品的属性)。

Autommaper CreateMissingTypeMaps 配置设置为true

我的课程:

public class Product 
{
    public int Id { get; set; }
}

public class Unity 
{
    public int Id { get; set; }
}

public class ProductDto 
{
    public int Id { get; set; }
    public UnityDto Unity{ get; set; }
}

public class UnityDto
{
    public int Id { get; set; }
}

测试代码

Product p = new Product() { Id = 1 };
Unity u = new Unity() { Id = 999 };
var a = new { Product = p, Unity = u };

var t1 = Mapper.Map<ProductDto>(a.Product); 
var t2 = Mapper.Map<UnityDto>(a.Unity);
var t3 = Mapper.Map<ProductDto>(a); 

Console.WriteLine(string.Format("ProductId: {0}", t1.Id)); // Print 1
Console.WriteLine(string.Format("UnityId: {0}", t2.Id)); // Print 999
Console.WriteLine(string.Format("Anonymous ProductId: {0}", t3.Id)); // Print 0 <<< ERROR: It should be 1 >>>
Console.WriteLine(string.Format("Anonymous UnityId: {0}", t3.Unity.Id)); // Print 999

配置文件中添加了两张地图:

CreateMap<Product, ProductDto>();
CreateMap<Unity, UnityDto>();

【问题讨论】:

  • 这个答案说在调用Map时传递设置:*.com/questions/17085878/…,但这是已知类型。
  • CreateMissingTypeMaps 已经在工作了。

标签: c#-4.0 automapper-5


【解决方案1】:

问题在于 Automapper 如何映射匿名对象。我没有时间查看 Automapper 源代码,但我通过对匿名对象的细微更改得到了所需的行为:

var a = new { Id = p.Id, Unity = u };

通过这样做,我什至可能会删除以前的映射,因为现在它只使用CreateMissingTypeMaps

注意:事实上,我不确定这是否真的是一个问题,或者我只是我的不切实际的期望。

【讨论】: