Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I map entities with lazy-loaded properties (without causing them to load)?

I'm using EF 4.1 and code-first in an MVC project, and AutoMapper to map entities to view models.

Prior to using code-first I was able to exclude navigation properties in order to prevent anything from being loaded that wasn't already. I'm using .Include() in my queries to include the references that I need in order to avoid additional database round-trips.

However, with code-first my entity only exposes an entity property (or ICollection if there are more than one). How can I know whether it has been loaded without triggering the load?

Assuming this can be done, is there a way to make this the default behavior for AutoMapper, so that I do not have to explicitly exclude members on every single entity?

like image 469
Morten Mertner Avatar asked Mar 20 '11 16:03

Morten Mertner


People also ask

How do I stop lazy loading in Entity Framework?

We can disable lazy loading for a particular entity or a context. To turn off lazy loading for a particular property, do not make it virtual. To turn off lazy loading for all entities in the context, set its configuration property to false.

What is the practice of delaying loading of navigation properties until they're actually needed?

Lazy loading is the practice of delaying load or initialization of resources or objects until they're actually needed to improve performance and save system resources.

What is lazy loading in Entity Framework?

Lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed. Lazy loading means delaying the loading of related data, until you specifically request for it.

What is lazy loading and how do you implement it?

One form of lazy loading is infinity scroll, in which, the content of the web page is loaded as and when the user scrolls down the page. It is a popular technique being used by various websites. Advantages of Lazy loading: On-demand loading reduces time consumption and memory usage thereby optimizing content delivery.


1 Answers

You can check whether a reference or collection navigation property of an entity has been loaded by:

bool isLoaded1 = dbContext.Entry(entity).Reference(e => e.MyReferenceProperty)
                     .IsLoaded();
bool isLoaded2 = dbContext.Entry(entity).Collection(e => e.MyCollectionProperty)
                     .IsLoaded();
like image 116
Slauma Avatar answered Nov 16 '22 17:11

Slauma