Skip to content

Commit

Permalink
Document UseQueryTrackingBehavior (#3635)
Browse files Browse the repository at this point in the history
Closes #3634
  • Loading branch information
roji authored Jan 3, 2022
1 parent a15b23c commit 8bfe379
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
8 changes: 8 additions & 0 deletions entity-framework/core/querying/tracking.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions samples/core/Querying/Tracking/BloggingContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
}
}
26 changes: 26 additions & 0 deletions samples/core/Querying/Tracking/NonTrackingBloggingContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using Microsoft.EntityFrameworkCore;

namespace EFQuerying.Tracking
{
public class NonTrackingBloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.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
}
}

0 comments on commit 8bfe379

Please sign in to comment.