Try this,
In Global.asax.cs
[Application_Start
], public static void AppInitialize()
protected void Application_Start(object sender, EventArgs e)
{
Mapper.CreateMap<Order, CustomerViewModel>()
.ForMember(destination => destination.OrderId, options => options.MapFrom(source => source.Id))
.ForMember(destination => destination.OrderName, options => options.MapFrom(source => source.Name));
Mapper.CreateMap<Customer, CustomerViewModel>()
.ForMember(destination => destination.CustmerId, options => options.MapFrom(source => source.Id))
.ForMember(destination => destination.CustmerName, options => options.MapFrom(source => source.Name))
.ForMember(destination => destination.OrderId, options => options.MapFrom(source => Mapper.Map<IEnumerable<Order>, IEnumerable<CustomerViewModel>>(source.Orders).FirstOrDefault().OrderId))
.ForMember(destination => destination.OrderName, options => options.MapFrom(source => Mapper.Map<IEnumerable<Order>, IEnumerable<CustomerViewModel>>(source.Orders).FirstOrDefault().OrderName));
}
And in your code call the mapper like below,
var lstCustomers = new List<Customer>
{
new Customer { Id = 1, Name="Name", Orders = new List<Order> { new Order { Id = 1000, Name ="Some Name"}}},
};
var result = Mapper.Map<IEnumerable<Customer>, IEnumerable<CustomerViewModel>>(lstCustomers);
I am presumed that you classes looks like below,
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public List<Order> Orders { get; set; }
}
public class Order
{
public int Id { get; set; }
public string Name { get; set; }
}
public class CustomerViewModel
{
public int CustmerId { get; set; }
public string CustmerName { get; set; }
public int OrderId { get; set; }
public string OrderName { get; set; }
}
Also refer this post.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…