Sobes.tech
Junior — Middle

At what stage does data loading from the database into application objects occur when using Entity Framework?

sobes.tech AI

Answer from AI

In Entity Framework, data loading from the database into application objects occurs at query execution time, i.e., when you access the database through LINQ queries or the context methods.

This is called lazy loading or eager loading, depending on the settings:

  • Eager Loading: data is loaded immediately when the query is executed, for example, using the Include method.
  • Lazy Loading: data is loaded when the navigation property of an object is accessed for the first time.

Thus, objects are created and populated with data at the moment of executing the database query, not at declaration or compilation.

Example:

using(var context = new AppDbContext())
{
    var users = context.Users.Include(u => u.Orders).ToList(); // Eager loading
}

Here, data from the Users table and related Orders are loaded into objects immediately upon calling ToList().