0

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

AutommaperCreateMissingTypeMaps配置设置为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>();
4

1 回答 1

1

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

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

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

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

于 2017-03-13T18:13:17.057 回答