SELECT all with children

dapper sql

Question

I have the following classes:

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; }
}

For returning a single order I use this method (any comment on it would also be helpful):

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;
            }
        }
    }

I know I can select all of my orders Id values into a collection on a separate query and run the above method in a foreach loop using the collection values as a parameter but I wonder if dapper has a more elegant solution for returning all of my orders instead of just one.

Accepted Answer

It sounds like you have a list or array of the ids; dapper supports parameter expansion, allowing use with in, for example:

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();
}

Any use?




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why