How to turn off query tracking on a context level in Entity Framework Core

In Entity Framework Core we’re used to setting AsNoTracking() direct on our queries, but it’s possible to set this on a global context level too. We can do this from our Startup.cs -> ConfigureServices method as shown below…

Setting query tracking behaviour globally

or we can set it on the context itself…

Setting query tracking behaviour globally

Why would we turn off query tracking for a whole DbContext?

Mostly you wouldn’t want to do this, but there is a couple of use cases where it’s useful such as when you have a read only site and know for sure no entities will need updating.

It could also be useful in a CQRS architecture when you have two DbContexts, one which is optimised for reads (eg. product catalogue) which has tracking turned off and one which is optimised for writes which has it turned on.

 

Leave a Reply

Your email address will not be published. Required fields are marked *