I see there are plenties of question on EF cache, but I have found no solution yet to my problem.
How do I completely disable Enti
If you want to completely ignore EF6's cache for data retrieval, then add AsNoTracking()
to the end of your query (before calling ToList()
or doing anything else that would execute the query.
MSDN on AsNoTracking()
Please note that doing so will neither check the cache for existing data, nor will it add the results of the database call to the cache. Additionally, Entity Framework will not automatically detect changes to entities that you retrieve from the database. If you do want to change any entities and save them back to the database, you'll need to attach the changed entities before calling SaveChanges()
.
Your method is currently:
public IList<Models.Example> GetAll()
{
return DataContext.example.ToList();
}
It would change to:
public IList<Models.Example> GetAll()
{
return DataContext.example.AsNoTracking().ToList();
}
If you are interested in other options for dealing with EF's cache, I've written a blog post about EF6 Cache Busting.
I had this trouble too, but I could fix it.
I'm using Repository Pattern and using default DI of .Net Core. I've been using AddSingleton(...), but it's wrong to use with DbContext.
So, I've changed to AddScoped, like I read from docs: Scoped lifetime services are created once per request.
It has solved my problem.
You must read this section from ms docs: Service Lifetimes and Registration Options