TheBoubou
TheBoubou

Reputation: 19903

ASP.NET MVC : Automapper to merge class

I have this code :

public class OrderModel
{
    public List<Order> Orders { get; set; }
}

public class Order
{
    public string Code { get; set; }
    public DateTime CreationDate { get; set; }
    public Customer Customer { get; set; }
}

public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

I'd like get a List<MyClass> MyClass look like :

public class MyClass
{
    public string OrderCode { get; set; }
    public string OrderCreationDate { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Automapper can help me for this ? if no other solution to avoid loop ?

Thanks,

Upvotes: 2

Views: 470

Answers (1)

Iridio
Iridio

Reputation: 9271

To do DTO flattening with automapper looks at this post and also this. They should answer your question.

If you don't want to use automapper I would use a simple Linq. Something like this

 var myClassList = (from p in OrderModel.Orders select new MyClass()
          {
            OrderCode = p.Code,
            OrderCreationDate = p.CreationDate,
            FirstName = p.Customer.FirstName,
            LastName = p.Customer.LastName
          }).ToList();

Upvotes: 2

Related Questions