Reputation: 4015
Suppose I have tables like=
I have seen some implementations where if we are trying to fetch data from Users table and we need related entity data also then we use
db.Users.Include(x=>x.User_Profile).Where(z=>z.ID==1).ToList()
But in my project even if I use
db.Users.Where(z=>z.ID==1).ToList()
I am still able to get related entities. Why this happens?
Upvotes: 2
Views: 957
Reputation: 17003
To answer your question you have to understand the fundamental ideas behind Lazy Loading and Eager loading in EF.
Eagerly Loading:
Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by use of the Include method. For example, your query below will load User with Id 1 and his profile.
db.Users.Include(x=>x.User_Profile).Where(z=>z.ID==1).ToList()
Lazy Loading:
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. 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. For example, when using the User entity class defined in your code, the related Profile/s will be loaded the first time the Proflie/s navigation property is accessed.
Turning off lazy loading for specific navigation properties
Turn off lazy loading for all entities:
public class MyDbContext: DbContext
{
public MyDbContext: ()
{
this.Configuration.LazyLoadingEnabled = false;
}
}
Explicit Loading :
Explicit loading is defined as : when objects are returned by a query, related objects are not loaded at the same time. By default, they are not loaded until explicitly requested using the Load method on a navigation property.
Resources:
https://msdn.microsoft.com/en-us/data/jj574232.aspx
Upvotes: 3