Automapper mapping with nested 1:M, M:1 relations

Viewed 67

I have relations like:

One-to-Many : Order-OrderDetails

Many-to-One : OrderDetails-Product

My Model:

public class Order
{ 
  public ICollection<OrderDetail> OrderDetails {get; set;}
}

public class OrderDetails
{
  public Order Order { get; set; }
  public Product Product {get; set;}
}

public class Product
{
  public ICollection<OrderDetail> OrderDetails { get; set; }
}

I have a couple of nested queries and I am trying to map my order to DTO. My order looks like:

| Order
|----OrderDetails
|    |----Product
|----OrderDetails
     |----Product

If my DTO looks like this:

public class OrderDetailsResponse
{
   .....

   public Order Order { get; set; }
}

How can I configure AutoMapper to achieve this? Any hints or suggestions would be highly appreciated.

Thank you.

1 Answers

AutoMapper should take care of the scenario if you have your entities set up correctly. The first thing I noticed is you might not have a very good understanding of relations. Check out this example for the details.

https://www.entityframeworktutorial.net/efcore/one-to-many-conventions-entity-framework-core.aspx

After you have the correct model setup, the following one line should suffice.

public AutoMapperProfile()
{
    CreateMap<Order, OrderDetailsResponse>();
}

And your models should be

public class Order
{  
    // Maybe some more properties

    public ICollection<OrderDetail> OrderDetails {get; set;}
}

public class OrderDetails
{  
    // Maybe some more properties

    public Product Product {get; set;}
}

public class Product
{  
    // Maybe some more properties

    // You do not need anything here.
}

You can see defined relations between models in two ways here. Now, your DTO could be

public class OrderDetailsResponse
{  
    // Maybe some more properties

    public ICollection<OrderDetail> OrderDetails { get; set; }
}
Related