Dapper选择嵌套对象

时间:2016-05-02 14:43:17

标签: c# sql-server orm dapper micro-orm

我的SQL看起来像

Select TOP 3 o.OrderId,
o.Total,
od.Quantity,
od.ItemDescription,
os.OrderStatusDescription,
os.OrderStatusID
 From dbo.Orders o
 INNER JOIN dbo.OrderStatuses os ON os.OrderStatusID = o.OrderStatusID
 INNER JOIN dbo.OrderDetails od ON od.OrderID = o.OrderID
  Where o.CustomerId = 100 order by OrderDate desc;

我的课程在c#侧如下,我在db端也有三个表。 我试图看看我是否可以使用dapper将3个表映射到一个对象顺序,而不必进行多个选择查询。 我需要从Order Table中排出前3行并加载其子表。 OrderDetail可以有1行orderId。

如何使用dapper选择1个嵌套对象?

 class Order{
      int OrderId {get;set;}      
      decimal Total {get;set;}
      List<OrderDetail> Details {get;set;}
      OrderStatus Status {get;set;}
 }

  class OrderDetail
  {
    int OrderLineId {get;set;}
    int OrderId {get;set;}  
    string ItemDescription {get;set;}
    int Quantity {get;set;}
  }

  class OrderStatus
  {
    int OrderStatusID {get;set;}
    string OrderStatusDescription {get;set;}
  }

这是我迄今为止尝试但未成功的

  sqlConnection.Open();

IEnumerable orders = sqlConnection
    .Query<Order>(
        @"select Order.*, OrderDetail.* 
          from Order join OrderDetail 
               inner join on Order.OrderId = OrderDetail.OrderId
               inner join on Order.OrderStatusID = OrderStatus.OrderId
               and Order.CustomerId = 100",
        (o, od, os) =>
            {
                o.Details = od;  //this is a List<OrderDetail>
                o.Status = os;
                return o;
            }); // 

enter image description here

1 个答案:

答案 0 :(得分:0)

有一些方法可以实现您的情况,但对我来说,您可以通过以下代码

来实现
var sql = @"Select TOP 3 o.OrderId,
    o.Total,
    os.OrderStatusID,
    os.OrderStatusDescription,
    od.OrderLineId,
    od.Quantity,
    od.ItemDescription       
    From dbo.Orders o
INNER JOIN dbo.OrderStatuses os ON os.OrderStatusID = o.OrderStatusID
INNER JOIN dbo.OrderDetails od ON od.OrderID = o.OrderID
Where o.CustomerId = 100 order by OrderDate desc;";


sqlConnection.Open();

var lookupOrders = new Dictionary<int,Order>();
var oders = sqlConnection.Query<Order, OrderStatus, OrderDetails, Order>(sql,
               (o, os, od) => 
               {
                    Order order;
                    if(!lookupOrders.ContainsKey(o.OrderId)){
                        lookupOrders.Add(o.OrderId, o);                            
                        order = o;
                        order.Details = new List<OrderDetail>();
                    }
                    else {
                        order = lookupOrders[o.OrderId];
                    }
                    order.Details.Add(od);
                    order.Status = os;
                    return order;
               }, splitOn: "OrderId, OrderStatusID, OrderLineId"
            ).Distinct();