Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit Lazy Loading vs Explicit Lazy Loading

I've been reading Entity Framework and people were crying over why there was not implicit lazy loading or something. Basically I've been searching things about Lazy Loading and now I know what it is : It is a design pattern which allows us to load objects when they are really needed.

But what is the difference between Explicit Lazy Loading and Implicit Lazy Loading.

Thanks in advance...

like image 610
Tarik Avatar asked Apr 04 '10 08:04

Tarik


People also ask

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.

Which is better lazy loading or eager loading?

Use Eager Loading when you are sure that you will be using related entities with the main entity everywhere. Use Lazy Loading when you are using one-to-many collections. Use Lazy Loading when you are sure that you are not using related entities instantly.

What are different types of loading available to load related entities in EF?

Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.

Is FirstorDefault lazy loading?

FirstorDefault() causes lazy loading or eager loading for linq to sql.


1 Answers

If you e.g. have an entity "OrderRow" and another entity "Order", there will be a navigational property on the OrderRow that points to the Order it belongs to.

Currently Entity Framework supports only Explicit Lazy Load which means that if you have retreived a number of OrderRows and want to check something on the Order you need to:

// or is an OrderRow
if(!or.Order.IsLoaded)
    or.Order.Load()

or.Order.Cancel();

However if you have implicit lazy loading you don't need the IsLoaded check, it will be done automatically, you can do or.Order.Cancel() directly and the Order will be loaded automatically if needed. This is how linq-to-sql works and it saves some typing and some risk for mistakes. On the other hand it makes it less clear exactly when and how database access will be performed. With implicit load it is easy to write inefficient code that makes one DB roundtrip for each line to be fetched from a table.

like image 172
Anders Abel Avatar answered Oct 29 '22 14:10

Anders Abel