选择所有带孩子的人

时间:2015-04-16 08:09:35

标签: sql dapper

我有以下课程:

public class Order
{
    public Order()
    {
        OrderItems = new List<OrderItem>();
    }
    public int Id { get; set; }
    public string OrderName { get; set; }

    public int OrderStatusId { get; set; }
    public OrderStatus Status { get; set; }

    public List<OrderItem> OrderItems { get; set; }
}

public class OrderItem
{
    public int Id { get; set; }
    public int OrderId { get; set; }
    public string ProductName { get; set; }
}

public class OrderStatus
{
    public int Id { get; set; }
    public string Description { get; set; }
}

对于返回单个订单,我使用此方法(对它的任何评论也会有帮助):

Order GetOrder()
    {
        using (var con = GetConnection())
        {
            try
            {
                con.Open();
                string query =
@"SELECT * FROM [Order] JOIN OrderStatus ON [Order].OrderStatusId =  OrderStatus.Id WHERE [Order].Id =1;
SELECT * FROM OrderItem Where OrderId = 1";

                using (var multi = con.QueryMultiple(query))
                {
                    Order order = multi.Read<Order, OrderStatus, Order>
                    ((ord, ordStat) => { ord.Status = ordStat; return ord; })
                    .FirstOrDefault();

                    order.OrderItems = multi.Read<OrderItem>().ToList();
                    return order;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }

我知道我可以在单独的查询中选择我的所有订单Id值到一个集合中,并使用集合值作为参数在foreach循环中运行上面的方法但是我想知道dapper是否更优雅返回所有订单的解决方案,而不仅仅是一个。

1 个答案:

答案 0 :(得分:0)

听起来你有一个列表或数组的ID; dapper支持参数扩展,允许与in一起使用,例如:

int[] ids = ...
string query =
@"SELECT * FROM [Order]
JOIN OrderStatus ON [Order].OrderStatusId =  OrderStatus.Id
WHERE [Order].Id in @ids;

SELECT * FROM OrderItem Where OrderId in @ids";

using (var multi = con.QueryMultiple(query, new { ids }))
{
    var orders = multi.Read<Order, OrderStatus, Order>
    ((ord, ordStat) => { ord.Status = ordStat; return ord; })
    .AsList();

    var orderItems = multi.Read<OrderItem>().ToLookup(x => x.OrderId);

    foreach(var order in orders) // pick out each order's items
        order.OrderItems = orderItems[order.Id].ToList();
}

有用吗?