Sitemap

๐€๐ฎ๐ญ๐จ๐ˆ๐ง๐œ๐ฅ๐ฎ๐๐ž ๐ข๐ง .๐๐„๐“

3 min readJan 1, 2025

--

๐Ÿš€ AutoInclude eliminates unnecessary overhead in your code, making it more efficient, while IgnoreAutoInclude allows you to exclude specific code segments. Letโ€™s explore how to use both features together!

In Entity Framework Core, AutoInclude is a feature that ensures certain navigation properties are automatically loaded in every query. This eliminates the need to use Include or ThenInclude repeatedly, as the related data is automatically included in your queries.

To implement the AutoInclude feature in ASP.NET Core using Entity Framework Core, you need to configure the relationships you want to include automatically using the ModelBuilder.

Letโ€™s start by using the AutoInclude feature in the Order model to ensure that OrderItems and Product relationships are automatically included in every Order query.

Press enter or click to view image in full size

This configuration ensures that the OrderItems and Product navigations are always automatically included in the Order and OrderItem entities. This way, you no longer need to manually use Include in every query for these relationships.

Get Beyza ErdoฤŸmuลŸโ€™s stories inย yourย inbox

Join Medium for free to get updates fromย thisย writer.

Letโ€™s first take a look at the method configurations in our generic repository.

Press enter or click to view image in full size

Before using AutoInclude, the Include method is used manually to load related data. Hereโ€™s an example of how this would look:

Press enter or click to view image in full size

After enabling AutoInclude, we can remove the Include statements from the GetOrderAsync method. Since AutoInclude automatically loads these relationships, there's no need to explicitly specify them anymore.

Press enter or click to view image in full size

IgnoreAutoInclude

Introduced in EF Core 7.0, the IgnoreAutoInclude feature allows you to exclude a navigation property configured with AutoInclude from being loaded in a specific query. IgnoreAutoInclude behaves like AsNoTracking() in EF Core queries, excluding AutoInclude relationships from the query.

Hereโ€™s an example: Without using IgnoreAutoInclude, a query like the one below automatically includes the OrderItems and Product relationships thanks to AutoInclude.

Press enter or click to view image in full size

For example, if we only want to view the Order information without including the related data, we need to use the IgnoreAutoInclude feature.

Press enter or click to view image in full size
Press enter or click to view image in full size

I hope you found this informative. See you in my upcoming posts! :)

--

--