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. 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.
Have I got that wrong? If so, how is the No Change Tracking
meant to work?
Note: I also tried the following code:
serviceCollection.AddDbContext<LibraryNoTrackingContext>(
o =>
{
o.UseSqlServer(configuration.GetConnectionString("Default"));
o.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
});
QueryTrackingBehavior.NoTracking
in the constructor was obeyed. Personally, I use that option by default to speed up queries, and explicitly call the appropriate methods when modifying/inserting/deleting data. 95% of my queries are reads - so in terms of your last sentence, I do that all the time!! – Pulse