diff --git a/entity-framework/core/querying/tracking.md b/entity-framework/core/querying/tracking.md index c8fcca9bef..aa91fe436b 100644 --- a/entity-framework/core/querying/tracking.md +++ b/entity-framework/core/querying/tracking.md @@ -41,6 +41,14 @@ Starting with EF Core 5.0, you can combine both of the above behaviors in same q [!code-csharp[Main](../../../samples/core/Querying/Tracking/Program.cs#NoTrackingWithIdentityResolution)] +## Configuring the default tracking behavior + +If you find yourself changing the tracking behavior for many queries, you may want to change the default instead: + +[!code-csharp[Main](../../../samples/core/Querying/Tracking/NonTrackingBloggingContext.cs?name=OnConfiguring&highlight=5)] + +This makes all your queries non-tracking by default. You can still add `AsTracking()` to make specific queries tracking. + ## Tracking and custom projections 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. diff --git a/samples/core/Querying/Tracking/BloggingContext.cs b/samples/core/Querying/Tracking/BloggingContext.cs index f5fa0cd162..759e0b8486 100644 --- a/samples/core/Querying/Tracking/BloggingContext.cs +++ b/samples/core/Querying/Tracking/BloggingContext.cs @@ -16,8 +16,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { - optionsBuilder.UseSqlServer( - @"Server=(localdb)\mssqllocaldb;Database=EFQuerying.Tracking;Trusted_Connection=True"); + optionsBuilder + .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFQuerying.Tracking;Trusted_Connection=True"); } } } diff --git a/samples/core/Querying/Tracking/NonTrackingBloggingContext.cs b/samples/core/Querying/Tracking/NonTrackingBloggingContext.cs new file mode 100644 index 0000000000..1bd5b84fe1 --- /dev/null +++ b/samples/core/Querying/Tracking/NonTrackingBloggingContext.cs @@ -0,0 +1,26 @@ +using Microsoft.EntityFrameworkCore; + +namespace EFQuerying.Tracking +{ + public class NonTrackingBloggingContext : DbContext + { + public DbSet Blogs { get; set; } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity() + .HasData( + new Blog { BlogId = 1, Url = @"https://devblogs.microsoft.com/dotnet", Rating = 5 }, + new Blog { BlogId = 2, Url = @"https://mytravelblog.com/", Rating = 4 }); + } + + #region OnConfiguring + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder + .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFQuerying.Tracking;Trusted_Connection=True") + .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); + } + #endregion + } +}