Invalidating/Disabling Entity Framework cache

前端 未结 2 747
渐次进展
渐次进展 2020-12-09 16:46

I see there are plenties of question on EF cache, but I have found no solution yet to my problem.

The straight question is

How do I completely disable Enti

相关标签:
2条回答
  • 2020-12-09 17:34

    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.

    0 讨论(0)
  • 2020-12-09 17:52

    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

    0 讨论(0)
提交回复
热议问题