简体   繁体   中英

Automapper mapping a list of ids to objects in many-to-many scenario

I'm looking for the best way to handle this with Automapper

My simplified domain model (all IDs are auto generated by the DB):

public class Product
{
    public long Id { get; set; }
    public List<OrderProduct> OrderProducts { get; set; }
}

public class Order
{
    public long Id { get; set; }
    public List<OrderProduct> OrderProducts { get; set; }
}

public class OrderProduct
{
    public long Id { get; set; }
    public long ProductId { get; set; }
    public long OrderId { get; set; }
    public Product Product { get; set; }
    public Order Order { get; set; }
}

My DTO object:

public class CreateOrderDTO
    {
        public long Id { get; set; }
        public List<long> ProductIds { get; set; }
    }

Now, I need to map from CreateOrderDTO to Order object. What is the best way to achieve this using automapper? I can map it using plain C# - however would really like to know the proper way to do this using Automapper.

Assuming that you already installed the Automapper.

Here's one way of configuring your mapping.

You create your mapping profile, you should inherit from the Profile object, then create your mapping in your profile's contructor:

public class OrderProfile : Profile
    {
        public OrderProfile()
        {
            CreateMap<CreateOrderDTO, Order>().ForMember(c => c.OrderProducts, m => m.MapFrom(l => CreateOrderProducts(l.ProductIds)));
        }

        private static List<OrderProduct> CreateOrderProducts(IList<long> productIds)
        {
            IList<OrderProduct> orderProducts = new List<OrderProduct>();

            foreach (long id in productIds)
            {
                orderProducts.Add(new OrderProduct
                {
                    ProductId = id
                });
            }

            return orderProducts.ToList();
        }
    }

Note: I feel that you need to manually map your ProductIds List<long> to List<OrderProduct> and you should do that in your profile as well.

Next, you configure a AutoMapper:

 public static class MappingConfig
    {
        public static MapperConfiguration Configure()
        {
            MapperConfiguration config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile<OrderProfile>();
            });

            return config;
        }
    }

This is one way of doing the configuration (ie adding your profile), thru the constructor of the MapperConfiguration, you can also do this with static Mapper instance http://docs.automapper.org/en/stable/Configuration.html .

Usage:

You can then create an instance of the mapper, preferably, you should only have one instance of mapper in your app, so it's always a good idea to register your mapper in your ioc container.

static void Main(string[] args)
        {
            var mapper = MappingConfig.Configure().CreateMapper();

            CreateOrderDTO dto = new CreateOrderDTO
            {
                Id = 1,
                ProductIds = new List<long> { 23L }
            };

            // Here it appears that it's as if you didn't do any manual mapping.
        Order order = mapper.Map<CreateOrderDTO, Order>(dto);
            Order order = mapper.Map<CreateOrderDTO, Order>(dto);

            Console.WriteLine("Order Id: " + order.Id);
        Console.WriteLine("Product Id: " + order.OrderProducts.Select(o => o.ProductId).First());
        Console.ReadLine();
        }

在此处输入图片说明

If find this unhelpful, you can vote it down, and I'll remove it as I want the readers not to be confused of the right ways of doing things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM