I want to map Order class with AutoMapper:
class Order
{
public int Id { get; set; }
public int Quantity { get; set; }
public Product Product { get; set; }
}
The Product class:
class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
I have created AutoMapper maps for both Order and Product classes. In Product class I skip the Id value.
The problem is that I want to map Order.Product as a reference. I can achieve it in this way:
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
This approach is not ok for me, because I have to set the .Product reference manualy, I want this to be done with AutoMapper. I don't want the nested Product property to be mapped in "classic way", I just need exactly the same reference in new object.
I have tried to solve this problem with using ResolveUsing method and IMemberValueResolver but without success, the AutoMapper still was mapping the nested Product property instead of seting its reference as same as in other Order object.
At first place you should ignore Product
property from initial mapping via mapping configuration, and then pass function, which will set newOrder
's Product
property, into AfterMap
method.
CreateMap<Order, Order>()
.ForMember(dest => dest.Product, opt => opt.Ignore())
.AfterMap((src, dest) =>
{
dest.Product = src.Product;
});
Mapping:
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With