[英]QueryTrackingBehavior has no Effect on DbContext
Perhaps my expectation requires resetting.也许我的期望需要重新设定。
I was doing a proof of concept for a "non-tracking" context.我正在为“非跟踪”上下文进行概念验证。 In the constructor of the context, I added the following lines:
在上下文的构造函数中,我添加了以下几行:
ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
ChangeTracker.Tracked += ChangeTracker_Tracked;
and the following handler:和以下处理程序:
private void ChangeTracker_Tracked(object sender, Microsoft.EntityFrameworkCore.ChangeTracking.EntityTrackedEventArgs e)
{
Debug.WriteLine("Tracking has commenced");
}
My expectation was that if I added an entity to the context, the Tracked
handler would not fire because of the NoTracking tracking behavior configuration.我的期望是,如果我将实体添加到上下文中,由于 NoTracking 跟踪行为配置,
Tracked
处理程序不会触发。 But when I add an entity, sure enough, the event fires!但是当我添加一个实体时,果然,事件触发了!
var pub = new Publishers
{
Name = "Blabla"
};
var ctx = serviceProvider.GetService<LibraryNoTrackingContext>();
ctx.Publishers.Add(pub);
By my observation, the QueryTrackingBehavior
configuration does not seem to be working, as change tracking is happening.根据我的观察,
QueryTrackingBehavior
配置似乎不起作用,因为正在发生更改跟踪。
Have I got that wrong?我错了吗? If so, how is the
No Change Tracking
meant to work?如果是这样,
No Change Tracking
是如何工作的?
Note: I also tried the following code:注意:我还尝试了以下代码:
serviceCollection.AddDbContext<LibraryNoTrackingContext>(
o =>
{
o.UseSqlServer(configuration.GetConnectionString("Default"));
o.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
});
Ok, I figured this out with a bit of experimentation.好的,我通过一些实验发现了这一点。 I'll leave this answer here for people looking into this.
我会把这个答案留给调查这个的人。
The QueryTrackingBehavior of QueryTrackingBehavior.NoTracking
is doing what it should be doing. QueryTrackingBehavior.NoTracking 的
QueryTrackingBehavior.NoTracking
正在做它应该做的事情。
My comprehension was the problem.我的理解是问题所在。
If you retrieve data, using a "no tracking" context, those entities will not be added to the ChangeTracker
.如果您使用“无跟踪”上下文检索数据,这些实体将不会添加到
ChangeTracker
中。
However, if you add entities to the context, even if it is a "no tracking" context, those entities will be tracked ie they will be added to the ChangeTracker
.但是,如果您将实体添加到上下文中,即使它是“无跟踪”上下文,也会跟踪这些实体,即它们将被添加到
ChangeTracker
中。
So, a "no tracking" context is still of value, if you want to use it for requests that will do not more than retrieve data.因此,如果您想将它用于不超过检索数据的请求,“无跟踪”上下文仍然是有价值的。 Every entity retrieved will not be tracked.
不会跟踪检索到的每个实体。
If you find yourself adding an entity to such a context, you may want to ask yourself why you need to be doing that.如果您发现自己将实体添加到这样的上下文中,您可能想问自己为什么需要这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.