Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Eager / Lazy loading examples in linq2sql

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

like image 543
Brendan Avatar asked Oct 23 '11 00:10

Brendan


People also ask

What is lazy loading example?

For example, if a web page has an image that the user has to scroll down to see, you can display a placeholder and lazy load the full image only when the user arrives to its location.

What is lazy loading in Entity Framework with example?

Lazy loading is delaying the loading of related data, until you specifically request for it. It is the opposite of eager loading. For example, the Student entity contains the StudentAddress entity.

What is lazy loading in LINQ?

What is Lazy Loading? Lazy Loading means the related entities are not loaded, until we iterate through them or bind them the data. By default, LINQ to SQL loads the related entities, using Lazy Loading. There is one-to-many relationship between Department and Employees entities.

What are eager lazy and explicit loading?

Explicit loading means that the related data is explicitly loaded from the database at a later time. Lazy loading means that the related data is transparently loaded from the database when the navigation property is accessed.


1 Answers

  • 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

like image 106
Mahmoud Gamal Avatar answered Oct 18 '22 22:10

Mahmoud Gamal