Examples of simple downloads / lazy downloads in linq2sql

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

+6
source share
1 answer
  • Delayed loading: for a given object, the collections associated with it may be empty at the first loading, but when these collections are repeated first, LINQ to SQL launches a query to load these collections after loading it, the collection is then available for future use without requesting another request:

    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 } } 

OrderDetails are only loaded if they are repeated, so if OrderDetatils never repeated, the corresponding request is never executed.

  • Unwanted loading: immediate loading of linked collections for all reference objects, for example LINQ to SQL automatically adds all OrderDetails for all returned 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: Delayed execution is a LINQ function , but Delayed loading is a LINQ to SQL function

+9
source

Source: https://habr.com/ru/post/899888/


All Articles