我想用AutoMapper映射Order类:
class Order
{
public int Id { get; set; }
public int Quantity { get; set; }
public Product Product { get; set; }
}
产品类:
class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
我为Order和Product类创建了AutoMapper贴图。在Product类中,我跳过Id值。
问题是我想将Order.Product映射为参考。我可以通过这种方式实现它:
var order = new Order { Id = 1, Quantity = 5, Product = new Product { Id = 1, Name = "CPU", Price = 500 } };
var newOrder = Mapper.Map<Order, Order>(order);
newOrder.Product = order.Product; // I want to newOrder.Product reference point to the same object as order.Product
这种方法对我来说不行,因为我必须手动设置.Product参考,我希望用AutoMapper来完成。我不希望嵌套的Product属性以“经典方式”映射,我只需要在新对象中使用完全相同的引用。
我尝试使用ResolveUsing方法和IMemberValueResolver解决了这个问题,但没有成功,AutoMapper仍然映射嵌套的Product属性,而不是像其他Order对象一样设置它的引用。
答案 0 :(得分:7)
首先,您应该通过映射配置从初始映射中忽略Product
属性,然后将将newOrder
的{{1}}属性设置为Product
的函数传递给AfterMap
方法
CreateMap<Order, Order>()
.ForMember(dest => dest.Product, opt => opt.Ignore())
.AfterMap((src, dest) =>
{
dest.Product = src.Product;
});
映射:
var order = new Order { Id = 1, Quantity = 5, Product = new Product { Id = 1, Name = "CPU", Price = 500 } };
var newOrder = Mapper.Map<Order, Order>(order);
//Ouputs: true
Console.WriteLine(Object.ReferenceEquals(newOrder.Product, order.Product));