VahidN/EFCoreSecondLevelCacheInterceptor

Q: The content of the entry in the cache after updating the entry via DbContext

Closed this issue · 1 comments

Hi, friend. Answer a couple of questions please. If I have a cache to store a selection from the table. after which, through the DbContext, I will update the record in the database. will the cache contain the new value of the record or will we just clear the cache and we will need to request data from the database again so that the new value is in the cache?

I am faced with the fact that after updating the entry, the cache is invalidated and I need to make one more request to the database in order for the entry to get into the cache.

await context.AddAsync(entity);
await context.SaveChangesAsync();

var where = context.Set()
.Where(dbEntity => dbEntity.Id.Equals(entity.Id))
.Cacheable(cacheConfiguration.ExpirationMode, cacheConfiguration.Timeout)
.FirstOrDefaultAsync(); <- here the record goes into the cache

var where1 = await context.Set()
.AsNoTrackingWithIdentityResolution()
.Where(dbEntity => dbEntity.Id.Equals(entity.Id))
.Cacheable(cacheConfiguration.ExpirationMode, cacheConfiguration.Timeout)
.FirstOrDefaultAsync(); <- here we get the entry from the cache

entity.Body = "test";
context.Update(entity);
await context.SaveChangesAsync(); <- invalidation

var where2 = await context.Set()
.AsNoTrackingWithIdentityResolution()
.Where(dbEntity => dbEntity.Id.Equals(entity.Id))
.Cacheable(cacheConfiguration.ExpirationMode, cacheConfiguration.Timeout)
.FirstOrDefaultAsync(); <- there is no entry in the cache since the invalidation of the entry occurred at the previous step. accordingly, the entry gets into the cache

var where3 = await context.Set()
.AsNoTrackingWithIdentityResolution()
.Where(dbEntity => dbEntity.Id.Equals(entity.Id))
.Cacheable(cacheConfiguration.ExpirationMode, cacheConfiguration.Timeout)
.FirstOrDefaultAsync(); <- here we get the entry from the cache

is this the expected behavior?

VahidN commented

is this the expected behavior?

Yes. It is.
This interceptor doesn't know what are you doing with your saved data and how does it affect thousands of cached data. It will track the affected tables and then it will remove the related cached data. All of them. It's fast. Next time with the next query, the cache will be updated based on the actual needs and fresh data.