Tracking vs. No-Tracking Queries
学习链接
Tracking queries
By default, queries that return entity types are tracking. A tracking query means any changes to entity instances are persisted by SaveChanges.
var blog = context.Blogs.SingleOrDefault(b => b.BlogId == 1);
blog.Rating = 5;
context.SaveChanges();
Keyless entity types are never tracked. Wherever this article mentions entity types, it refers to entity types which have a key defined.
No-tracking queries
No-tracking queries are useful when the results are used in a read-only scenario. They’re generally quicker to execute because there’s no need to set up the change tracking information. If the entities retrieved from the database don’t need to be updated, then a no-tracking query should be used. An individual query can be set to be no-tracking. A no-tracking query also give results based on what’s in the database disregarding any local changes or added entities.
var blogs = context.Blogs.AsNoTracking().ToList();context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
var blogs = context.Blogs.ToList();
Configuring the default tracking behavior
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFQuerying.Tracking;Trusted_Connection=True").UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
}
Even if the result type of the query isn’t an entity type, EF Core will still track entity types contained in the result by default. In the following query, which returns an anonymous type, the instances of Blog in the result set will be tracked.
var blog = context.Blogs.Select(b =>new { Blog = b, PostCount = b.Posts.Count() });
You can configure a navigation in the model to be included every time the entity is loaded from the database using AutoInclude method. It has same effect as specifying Include with the navigation in every query where the entity type is returned in the results. Following example shows how to configure a navigation to be automatically included.
modelBuilder.Entity<Theme>().Navigation(e => e.ColorScheme).AutoInclude();
If for a particular query you don’t want to load the related data through a navigation, which is configured at model level to be auto-included, you can use IgnoreAutoIncludes method in your query. Using this method will stop loading all the navigations configured as auto-include by the user. Running a query like below will bring back all themes from database but won’t load ColorScheme even though it’s configured as auto-included navigation.
using (var context = new BloggingContext())
{var themes = context.Themes.IgnoreAutoIncludes().ToList();
}