title: Optimizing a LINQ to SQL query
body: <p>I have a query that looks like this:</p>
  
  <pre><code>public IList&lt;Post&gt; FetchLatestOrders(int pageIndex, int recordCount)
  {
      DatabaseDataContext db = new DatabaseDataContext();
      return (from o in db.Orders
              orderby o.CreatedDate descending
              select o)
              .Skip(pageIndex * recordCount)
              .Take(recordCount)
              .ToList();
  }
  </code></pre>
  
  <p>I need to print the information of the order and the user who created it:</p>
  
  <pre><code>foreach (var o in FetchLatestOrders(0, 10))
  {
      Console.WriteLine("{0} {1}", o.Code, o.Customer.Name);
  }
  </code></pre>
  
  <p>This produces a SQL query to bring the orders and one query for each order to bring the customer. Is it possible to optimize the query so that it brings the orders and it's customer in one SQL query?</p>
  
  <p>Thanks</p>
  
  <p>UDPATE: By suggestion of sirrocco I changed the query like this and it works. Only one select query is generated:</p>
  
  <pre><code>public IList&lt;Post&gt; FetchLatestOrders(int pageIndex, int recordCount)
  {
      var options = new DataLoadOptions();
      options.LoadWith&lt;Post&gt;(o =&gt; o.Customer);
      using (var db = new DatabaseDataContext())
      {
          db.LoadOptions = options;
          return (from o in db.Orders
                  orderby o.CreatedDate descending
                  select o)
                  .Skip(pageIndex * recordCount)
                  .Take(recordCount)
                  .ToList();
      }
  }
  </code></pre>
  
  <p>Thanks sirrocco.</p>