Invalidating/Disabling Entity Framework cache

c# caching entity-framework linq

Accepted Answer

When retrieving data from EF6, if you wish to completely disregard the cache, addAsNoTracking() the conclusion of your inquiry (prior to phoningToList() or doing any other action that would carry out the query.

on MSDNAsNoTracking()

Please be aware that doing so will neither add the outcomes of the database call to the cache, nor will it check the cache for already-existing data. Additionally, when you get entities from the database, Entity Framework won't immediately identify any modifications to those entities. You must attach the modified entities before calling if you wish to change any entities and save them back to the database.SaveChanges() .

Your approach at the moment is:

public IList<Models.Example> GetAll()
{
    return DataContext.example.ToList();
}

It would become:

public IList<Models.Example> GetAll()
{
    return DataContext.example.AsNoTracking().ToList();
}

I've written a article on the EF6 Cache Busting blog if you're interested in different options for handling EF's cache.

40
2/22/2016 3:24:15 AM

Popular Answer

I was having a similar issue, but I could remedy it.

Repository Pattern and.Net Core's built-in DI are both being used by me. I have been using AddSingleton(...), but utilizing DbContext with it is incorrect.

Therefore, I changed to AddScoped, as I saw in the documentation: Once each request, a scoped lifetime service is created.

My issue has been resolved.

You must read the following from Microsoft Docs: Service Lifetimes and Options for Registration



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow