Answering Mats' Challenge

time to read 3 min | 494 words

Mats Helander has a challenge for OR/M developers, and Mats should know, since he is behind NPersist.

Go for the post for details, but basically it is loading all Customer->Orders->OrderLines graph in 3 statements or less.

Because I am a sucker for challenges, I implemented it with ActiveRecord. In Mats' terms, the code is so simple it hurts, and yes, I cheated :-)

internal static IList<Customer> LoadCustomersOrdersAndOrderLines()

{

    Customer[] customers = Customer.FindAll();

    Order[] orders = Order.FindAll();

    OrderLine[] orderLines = OrderLine.FindAll();

    foreach (Customer customer in customers)

    {

        customer.Orders = new List<Order>();//avoid lazy load when adding

    }

 

    foreach (Order order in orders)

    {

        order.OrderLines = new List<OrderLine>();//avoid lazy load when adding

        order.Customer.Orders.Add(order);

    }

 

    foreach (OrderLine line in orderLines)

    {

        line.Order.OrderLines.Add(line);

    }

    return customers;

}