Tracking vs. No-Tracking Queries

本文讨论了EntityFrameworkCore中的跟踪查询和非跟踪查询,介绍了如何配置默认追踪行为,以及如何控制自动包含导航属性。重点在于何时选择使用哪种查询策略以优化性能和数据加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习链接

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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悠悠虾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值