EF Change Tracking good practices
When we use Entity Framework in our projects, there is a powerful feature enabled by default in our queries: Change Tracking (Also, can be set disabled explicitly). This feature keeps track of all changes applied to our entities. Its purpose is to simplify how changes are synchronized with the database, improving the overall performance. However, misuse can degrade performance since Change Tracking increases memory and CPU usage.
In some cases, Change Tracking is not necessary and can be disabled to reduce resource usage. A common example is when we only need to retrieve data for display purposes. In this scenario, tracking changes in the context provides no benefit.
How can I disable it and when?
There are different ways to accomplish this, depending on your specific needs. Here are the methods and practices I use to optimize my queries. If you have any suggestions for improvement or additions, feel free to share them in the comments! Also, all this informations is explained in the Official Microsoft Documentation.
- Tracking vs. No-Tracking Queries - EF Core | Microsoft Learn
- EntityFrameworkQueryableExtensions.AsNoTracking
Method
AsNoTracking()
Change Tracking will be disabled so changes made to the entities won’t persist when DbContext