Search code examples
c#-4.0automapper-5

Automapper: map an anonymous/dynamic type


I need some help to map an anonymous object using Automapper. The goal is combine Product and Unity in a ProductDto (in which unity is a product's property).

Autommaper CreateMissingTypeMaps configuration is set to true.

My Classes:

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; }
}

Test Code

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

There are two maps added to the profile:

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

Solution

  • The problem is how Automapper map anonymous objects. I haven't time to check out Automapper source code but I got the desired behaviour with minor changes on my anonymous object:

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

    By doing this, I might even delete previous mappings because now it is using only CreateMissingTypeMaps.

    Note: As matter of fact I'm not sure if it is really an issue or I it was just my unreal expectations.