How to: Control How Much Related Data Is Retrieved

Use the LoadWith method to specify which data related to your main target should be retrieved at the same time. For example, if you know that you will need information about the customers' orders, you can use LoadWith to make sure that the order information is retrieved at the same time as the customer information. This approach results in only one trip to the database for both sets of information.

You can retrieve data related to the main target of your query by retrieving a cross-product as one large projection, such as retrieving orders when you target customers. But this approach often has disadvantages. For example, the results are just projections and not entities that can be changed and persisted by Telerik Data Access. And you can be retrieving lots of data that you do not need.

In the following example, all the Orders for all the Customers who are located in Germany are retrieved when the query is executed. As a result, successive access to the Orders property on a Customer object does not trigger a new database query.

C#


    using (NorthwindDbContext dbContext = new NorthwindDbContext())
    {
       Telerik.OpenAccess.FetchOptimization.FetchStrategy fetchStrategy = new Telerik.OpenAccess.FetchOptimization.FetchStrategy();
       fetchStrategy.LoadWith<Customer>(c => c.Orders);
       dbContext.FetchStrategy = fetchStrategy;

       IQueryable<Customer> query = from c in dbContext.Customers
                                       where c.Country == "Germany"
                                       select c;

       foreach (Customer customer in query)
       {
           Console.WriteLine("Customer Id: {0}", customer.CustomerID);
           foreach (Order order in customer.Orders)
           {
               Console.WriteLine("===Order date: {0}", order.OrderDate.ToString());
           }
       }
    }

VB.NET


    Using dbContext As New NorthwindDbContext()
     Dim fetchStrategy As New Telerik.OpenAccess.FetchOptimization.FetchStrategy()
     fetchStrategy.LoadWith(Of Customer)(Function(c) c.Orders)
     dbContext.FetchStrategy = fetchStrategy

     Dim query As IQueryable(Of Customer) = From c In dbContext.Customers
                                            Where c.Country = "Germany"
                                            Select c

     For Each customer_Renamed As Customer In query
      Console.WriteLine("Customer Id: {0}", customer_Renamed.CustomerID)
      For Each order_Renamed As Order In customer_Renamed.Orders
       Console.WriteLine("===Order date: {0}", order_Renamed.OrderDate.ToString())
      Next order_Renamed
     Next customer_Renamed
    End Using

See Also