问题描述
我注意到可以通过三种不同的方式禁用跟踪:
- 通过
AsNoTracking
上下文属性 - 通过
context.ChangeTracker.QueryTrackingBehavior
通过执行最终查询之前的
AsNoTracking
进行执行 这三个之间是否有区别
如果我以前在每个上下文属性后都使用了 AsNoTracking
,现在我可以使用这种方法?
ChangeTracker
禁用它)? 和是 IQueryable< T>
,因此与查询的状态相关联,而不是与特定实体相关联(它们在 DbSet< T>
级别可用)只是因为它实现了 IQueryable< T>
)-请注意方法说明中的 all 字样:
AsNoTracking
AsTracking
两者都说:
换句话说,如果查询返回实体并且没有 AsNoTracking
或 AsTracking
在查询表达式树中的任意位置调用 ,查询使用 ChangeTracker.QueryTrackingBehavior
的值。
所以您的问题的答案是肯定的,您可以通过对最终查询的单个调用或通过 ChangeTracker
来达到相同的效果。
但是要注意一件事,文档中没有解释。如果查询表达式树包含多个 AsNoTracking
/ AsTracking
调用,则 last 调用优先。这意味着,通过将 AsNoTracking
添加到最终查询中,或者如果将 AsTracking
添加到最终查询中,则无论其内部如何跟踪行为调用或 ChangeTracker
属性。
I noticed that it is possible to disable tracking in three different ways:
- via
AsNoTracking
on context properties - via
AsNoTracking
on the final query before executing it - via
context.ChangeTracker.QueryTrackingBehavior
Is there any difference between these three approaches if I want to disable tracking for everything?
If I previously used AsNoTracking
after each context property and now I replace it with only a single call on the final query (or disable it via the ChangeTracker
) will it have the same effect?
AsNoTracking
and AsTracking
are extension methods of IQueryable<T>
, thus are associated with the state of the query and not a specific entity (the fact that they are available at DbSet<T>
level is just because it implements IQueryable<T>
) - note the word all inside the method descriptions:
AsNoTracking
AsTracking
And both say:
In other words, if the query returns entities and there is no AsNoTracking
or AsTracking
calls anywhere in the query expression tree, the query uses the value of the ChangeTracker.QueryTrackingBehavior
.
So the answer to your question is yes, you can achieve the same effect with a single call on the final query or via ChangeTracker
.
There is one thing to note though, which is not explained in the documentation. If the query expression tree contains more than one AsNoTracking
/ AsTracking
calls, the last call takes precedence. Which means that by adding AsNoTracking
or if you add AsTracking
to the final query will control it's behavior regardless of the any inner tracking behavior calls or ChangeTracker
property.
这篇关于AsNoTracking有关上下文属性,查询还是ChangeTracker?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!