Search code examples
entity-frameworklazy-loadingeager-loading

Lazy and Eager Loading in Entity Framework gives same result while using .Include() in both?


I have tried to implement lazy and eager loading in EF. Everything seems fine, but the .Include() method is available in both cases and returns the same results irrespective of lazy loading false or true.

I have 2 tables categories and product. Category can have multiple products and related using foreign key.

When I load categories using lazy loading by using .Include("Products"), it loads all products related to categories.

Same behavior is shown by eager loading.

var results = objDB.Categories.Include("Products").ToList(); // Enabled lazy load

var results = objDB.Categories.Include("Products").ToList(); // Disabled lazy load

Above both lines have same result. Please clarify this confusion.

.Include should not be available in case of lazy loading = true.

Please give your valuable opinion. Thanks in advance.


Solution

  • When you're explicitly using Include(), you're preforming an Eager Loading. Obviously, disabling/enabling Lazy Loading has no effect.

    The difference will be reflected when you'll omit the Include and try to access the Products navigation-property in some of your Category instances. When Lazy-Loading is enabled, EF will load it from the database. When it's disabled, you'll get null.