Search code examples
.netentity-frameworklazy-loadingproxy-classes

How Entity Framework uses proxy classes to support lazy loading?


I want to have an understanding of how Entity Framework uses Proxy classes? Why Entity Framework needs Proxy classes? What actually happens behind the scenes when Lazy loading is Enabled?


Solution

  • It's a decorator that adds lazy loading capabilities to an entity object by -

    • Storing a reference to the context.
    • Overriding navigation properties to make them load when they're accessed, using the context.

    The proxy inherits from the entity class. Therefore, the navigation properties must be virtual and the entity class can't be sealed.

    Maybe the most instructive way of understanding them is by seeing what it takes to implement lazy loading without proxies.