Showing posts with label AsNoTracking. Show all posts
Showing posts with label AsNoTracking. Show all posts

Monday, April 6, 2020

Combining SQL Queries with LINQ Queries

We have seen different ways of executing LINQ queries and ways to execute SQL queries from EF Core DBContext in isolation, now we shall see on how to combine SQL Queries with LINQ queries and execute them as a single query.

Let us get the list of Employees from the Employee table using SQL query and use the Include extension method to get the related department details as follows.

Friday, April 3, 2020

Tracking and No Tracking in Entity Framework Core

Tracking vs No-Tracking queries

Entities retrieved using Entity Framework Core LINQ queries have tracking enabled by default, this allows us to make changes to the entity and save them back to the database using SaveChanges.

Tracking can be disabled at a query level by adding AsNoTracking extension method to the query. For queries which retrieve large amount of read-only data it is recommended to disable tracking to improve performance. Disabling tracking helps us to gain some performance and also save on memory since we don’t have to save tracking information in the cache.

To disable tracking at the context level we need to set NoTracking to the QueryTrackingBehavior property as follows.

No-tracking queries in Entity Framework Core

Entities retrieved using Entity Framework Core have tracking enabled by default, however there are some situations in which we will not need tracking. Let us say we need to load a Grid in the UI with a large amount of data which will not be updated in this case we will not need tracking since the data is read-only.