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?
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.
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.
Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With