AmitykSharma
AmitykSharma

Reputation: 127

Lazy loading Entity framework

I started with database first approach with a many to one relation between Employee and Department. Two partial classes were created by Entity framework: Department having collections of Employee and Employee having single object Department.

If I added virtual then Department loads the related employees. There is no Inhertence relation ship between two classes. both are TPT.

I got this link saying

Lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook.

So how is this happening? Department is not the Parent for Employee.

Upvotes: 0

Views: 349

Answers (2)

Jenish Rabadiya
Jenish Rabadiya

Reputation: 6766

It seems you are confused about how proxy can do this.

So when you get the employee.Department property loaded with instance of Department, the instance employee is not of type Employee--instead it is of the type proxy class generated by EF and inherited from your Employee class. The allows the proxy type to override the Department property from the Employee class and that property's get method fires the database query to load the department instance into memory.

However you can also disable that behavior of proxy creation.

DbContext.Configuration.ProxyCreationEnabled = false;

Upvotes: 1

BJ Myers
BJ Myers

Reputation: 6813

Entity framework navigation properties work differently depending on whether you use a database-first or code-first approach. Here's an expanded snippet from the link you posted:

When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook.

"POCO" means "plain old CLR object," which are the classes you would create in a code-first approach. Since those classes don't have any inherent knowledge of EF, you have to define your properties in such a way that the EF proxies can connect them correctly.

Since you are using database-first, the classes are not "POCO." They inherit from an entity framework base class that wires up the navigation properties for lazy loading.

Upvotes: 2

Related Questions