Dapper icon indicating copy to clipboard operation
Dapper copied to clipboard

Mapping does not work properly

Open MarvinKlein1508 opened this issue 3 years ago • 0 comments

I found this strange behaviour when mapping with dapper. Consider this example:

SELECT 
*
FROM `order` o
INNER JOIN `order_product` op ON op.order_id = o.order_id
WHERE o.order_id = 5153

I map this query using C# in the following way:

Dictionary<int, Order> orders = new Dictionary<int, Order>();

            var tmp = await connection.QueryAsync<Order, OrderProduct, Order>(@"SELECT 
*
FROM `order` o
INNER JOIN `order_product` op ON op.order_id = o.order_id
WHERE o.order_id = 5153", (order, product) =>
            {

                //person
                Order orderEntity;
                //trip
                if (!orders.TryGetValue(order.order_id, out orderEntity))
                {
                    orders.Add(order.order_id, orderEntity = order);
                }


                // Products
                if (orderEntity.Products == null)
                {
                    orderEntity.Products = new List<OrderProduct>();
                }

                if (product != null)
                {
                    if (!orderEntity.Products.Any(x => x.order_product_id == product.order_product_id))
                    {
                        orderEntity.Products.Add(product);
                    }
                }

                return orderEntity;
            }, splitOn: "order_id");

As you can see I'm selection all from both tables. However the property order_product_id is always 0.

When I run this query instead: var products = await connection.QueryAsync<OrderProduct>("SELECT * FROM order_product where order_id = 5153");

I will get the order_product_id.

When I change the SQL from my main query to select this: o.*, op.*, op.order_product_id

The order_product_id property will be set. But only if I select it as above.

The class for OrderProduct is a 1:1 representation of the DB.

public class OrderProduct
    {
        public int order_product_id { get; set; }
        public int order_id { get; set; }
        public int product_id { get; set; }
        public string name { get; set; }
        public string model { get; set; }
        public int quantity { get; set; }
        public decimal price { get; set; }
        public decimal total { get; set; }
        public decimal tax { get; set; }
        public int reward { get; set; }
    }

MarvinKlein1508 avatar Mar 23 '22 11:03 MarvinKlein1508