Invalidating/Disabling Entity Framework cache

前端 未结 2 755
渐次进展
渐次进展 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 GetAll()
    {
        return DataContext.example.ToList();
    }
    

    It would change to:

    public IList 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.

提交回复
热议问题