提问者:小点点

使用Dapper映射到嵌套对象


我有一个对象,有2个类列表。

public class Order
{
    int order_id;
    double amount;
    List<order_item> order_items;
    List<order_shipment> order_shipments;
}

下面是映射对象的方法:

SELECT * FROM Orders o
INNER JOIN Order_Items i ON i.order_id = o.order_id
INNER JOIN Order_Shipments s ON s.order_id = o.order_id

将上述查询映射到嵌套类的方法是什么?


共1个答案

匿名用户

试一试:

var orders = 
    conn.Query<Order, order_item, order_shipment>(@"
            SELECT o.*,i.*,s.* FROM Orders o
            INNER JOIN Order_Items i ON i.order_id = o.order_id
            INNER JOIN Order_Shipments s ON s.order_id = o.order_id 
        ", (order, orderItem, orderShipment) => {
            order.order_items = order.order_items ?? new List<order_item>();
            order.order_items.Add(orderItem);
             
            order.order_shipments = order.order_shipments ?? new List<order_shipment>();
            order.order_shipments.Add(orderShipment);
            
            return order;
        }).AsQueryable();