Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private constructor on POCO entity preventing lazy loading

I have a POCO entity on which I have defined a custom constructor. I have also implemented the default constructor so that Entity Framework can successfully hydrate the object when I request a copy from the database.

This seems to work well but when I set the default constructor to private (to force my code to use the custom version) and request an entity from the database, I don't seem to be able to navigate over related entities as they are all null.

This seems to be a lazy loading problem so I could change my repository to eager load the related objects I need but am wondering if there is a better way to hide the default constructor from the client code whilst allowing Entity Framework to lazy load?

like image 318
James Avatar asked Mar 28 '12 12:03

James


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.

Which entity will allow lazy loading?

Yes, lazy loading is enabled in the Entity Framework ORM too, it is on by default in Entity Framework, so if you want to enable lazy loading in Entity Framework, you don't need to do anything.

Does Entity Framework support lazy loading?

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

Is lazy loading enabled by default in Entity Framework Core?

The advice is not to use lazy loading unless you are certain that it is the better solution. This is why (unlike in previous versions of EF) lazy loading is not enabled by default in Entity Framework Core.


1 Answers

If you define private constructor you violate requirements for creating POCO proxy responsible for lazy loading:

A custom data class must have a public or protected constructor that does not have parameters.

So the best option for you is using protected constructor or not using lazy loading.

like image 140
Ladislav Mrnka Avatar answered Oct 26 '22 13:10

Ladislav Mrnka