0
我需要一些幫助來使用Automapper映射一個匿名對象。目標是在ProductDto中將Product和Unity結合在一起(在此統一體中是產品的屬性)。Automapper:映射一個匿名/動態類型
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
有兩種MAPPS添加到配置文件:
CreateMap<Product, ProductDto>();
CreateMap<Unity, UnityDto>();
這個答案說在調用Map時傳入設置:http://stackoverflow.com/questions/17085878/automapper-auto-create-createmap,但這是與已知的類型。 – ps2goat
CreateMissingTypeMaps已經在工作。 –