Edit

Share via


How to: Retrieve Many Objects At Once

You can retrieve many objects in one query by using LoadWith.

Example

The following code uses the LoadWith method to retrieve both Customer and Order objects.

Northwnd db = new Northwnd(@"northwnd.mdf");
DataLoadOptions ds = new DataLoadOptions();
ds.LoadWith<Customer>(c => c.Orders);
ds.LoadWith<Order>(o => o.OrderDetails);
db.LoadOptions = ds;

var custQuery =
    from cust in db.Customers
    where cust.City == "London"
    select cust;

foreach (Customer custObj in custQuery)
{
    Console.WriteLine($"Customer ID: {custObj.CustomerID}");
    foreach (Order ord in custObj.Orders)
    {
        Console.WriteLine($"\tOrder ID: {ord.OrderID}");
        foreach (OrderDetail detail in ord.OrderDetails)
        {
            Console.WriteLine($"\t\tProduct ID: {detail.ProductID}");
        }
    }
}

See also