Loadings in Entity Framework

Posted by

Loadings in Entity Framework Core refer to the process of loading related data, or “navigation properties,” of an entity.

In Entity Framework Core, you can specify which navigation properties should be loaded along with the main entity, either explicitly or implicitly.

In Entity Framework, there are three main ways to load entities: eager loading, lazy loading, and explicit loading.

  1. Eager Loading: In this method, all related entities are loaded into memory along with the main entity. The related entities are loaded in a single query, which minimizes the number of round trips to the database. You can use the Include method in your query to specify which related entities should be eager-loaded. For example:
var student = context.Students
                    .Include(s => s.Enrollments.Select(e => e.Course))
                    .FirstOrDefault();

In the example above, the query will load the first student along with all of their enrollments and the courses they are enrolled in.

  1. Lazy Loading: In this method, related entities are loaded into memory only when they are accessed. For example:
var student = context.Students.FirstOrDefault();
var enrollments = student.Enrollments;

In this example, the first query will load the first student, and the second query will load the related enrollments only when they are accessed. This can save on memory usage, but it can also result in additional round trips to the database if multiple related entities are accessed.

  1. Explicit Loading: In this method, you can choose to explicitly load related entities when needed, instead of relying on eager or lazy loading. You can use the Load method in your query to explicitly load related entities. For example:
var student = context.Students.FirstOrDefault();
context.Entry(student).Collection(s => s.Enrollments).Load();

In this example, the first query will load the first student, and the second query will explicitly load the related enrollments. This gives you more control over when and how related entities are loaded, but it also requires more code and increases the number of round trips to the database.

In summary, the choice of loading method will depend on your specific use case, and the trade-offs between memory usage, performance, and code complexity.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.