title: IQueryable and lazy loading
body: <p>I'm having a hard time determining the best way to handle this...  With Entity Framework (and L2S), LINQ queries return IQueryable.  I have read various opinions on whether the DAL/BLL should return IQueryable, IEnumerable or IList.  Assuming we go with IList, then the query is run immediately and that control is not passed on to the next layer.  This makes it easier to unit test, etc.  You lose the ability to refine the query at higher levels, but you could simply create another method that allows you to refine the query and still return IList.  And there are many more pros/cons.  So far so good.</p>
  
  <p>Now comes Entity Framework and lazy loading.  I am using POCO objects with proxies in .NET 4/VS 2010.  In the presentation layer I do:</p>
  
  <pre><code>foreach (Order order in bll.GetOrders())
  {
    foreach (OrderLine orderLine in order.OrderLines)
    {
      // Do something
    }
  }
  </code></pre>
  
  <p>In this case, GetOrders() returns IList so it executes immediately before returning to the PL.  But in the next foreach, you have lazy loading which executes multiple SQL queries as it gets all the OrderLines.  So basically, the PL is running SQL queries "on demand" in the wrong layer.</p>
  
  <p>Is there any sensible way to avoid this?  I could turn lazy loading off, but then what's the point of having this "feature" that everyone was complaining EF1 didn't have?  And I'll admit it is very useful in many scenarios.  So I see several options:</p>
  
  <ol>
  <li>Somehow remove all associations in the entities and add methods to return them.  This goes against the default EF behavior/code generation and makes it harder to do some composite (multiple entity) LINQ queries.  It seems like a step backwards.  I vote no.</li>
  <li>If we have lazy loading anyway which makes it hard to unit test, then go all the way and return IQueryable.  You'll have more control farther up the layers.  I still don't think this is a good option because IQueryable ties you to L2S, L2E, or your own full implementation of IQueryable.  Lazy loading may run queries "on demand", but doesn't tie you to any specific interface.  I vote no.</li>
  <li>Turn off lazy loading.  You'll have to handle your associations manually.  This could be with eager loading's .Include().  I vote yes in some specific cases.</li>
  <li>Keep IList and lazy loading.  I vote yes in many cases, only due to the troubles with the others.</li>
  </ol>
  
  <p>Any other options or suggestions?  I haven't found an option that really convinces me.</p>