Simple Eager / Lazy loading examples in linq2sql

后端 未结 1 1615
借酒劲吻你
借酒劲吻你 2021-01-12 16:54

Does anyone have a simple code example in linq2sql that demonstrates the difference between Eager Loading and Lazy Loading?

相关标签:
1条回答
  • 2021-01-12 17:26
    • Deferred Loading: for a given entity, it's associated collections may be empty when it is first loaded, but when these collections are first iterated, LINQ to SQL fires off a query to load these collections after it is loaded the collection is then available for future use without requiring another query:

      var query = from o in db.GetTable<Order>() //db is the datacontext
              select o;
      foreach(Order o in query)
      {
          foreach(OrderDetail d in o.OrderDetails)//Deferred loading
          {
             //Do something on these collections
          }
      }
      

    The OrderDetails are loaded only if it is iterated, so If the OrderDetatils are never iterated the corresponding query is never executed.

    • Eager Loading: immediate loading the associated Collections for all referenced entities for example LINQ to SQL will automatically brings all the OrderDetails for all the retreived Orders

      DataLoadOptions op = new DataLoadOptions();
      op.LoadWith<Order>(o => o.OrderDetails);
      db.LoadOptions = op;
      var query = from o in db.GetTable<Order>() 
               select o;
      foreach(Order o in query)
      { 
          //Order details are eager loaded; additional queries are not needed
          foreach(OrderDetail d in o.OrderDetails)
          {
             //do something
          }
      }
      

    note that: Deferred execution is a LINQ Feature but Deferred Loading is a LINQ to SQL feature

    0 讨论(0)
提交回复
热议问题