How to: Filter Related Data

 

Use the AssociateWith method to specify sub-queries to limit the amount of retrieved data.

Example

In the following example, the AssociateWith method limits the Orders retrieved to those that have not been shipped today. Without this approach, all Orders would have been retrieved even though only a subset is desired.

Northwnd db = new Northwnd(@"c:\northwnd.mdf");
DataLoadOptions dlo = new DataLoadOptions();
dlo.AssociateWith<Customer>(c => c.Orders.Where(p => p.ShippedDate != DateTime.Today));
db.LoadOptions = dlo;
var custOrderQuery = 
    from cust in db.Customers
    where cust.City == "London"
    select cust;

foreach (Customer custObj in custOrderQuery)
{
    Console.WriteLine(custObj.CustomerID);
    foreach (Order ord in custObj.Orders)
    {
        Console.WriteLine("\t {0}",ord.OrderDate);
    } 
}
Show: