5

I've recently started using the sql version of IDistributedCache on a dotnet core web api.

How would you remove/invalidate a set of keys for say a specific user?

I.e: I structured the keys to follow this convention:

/users/{userId}/Key1
/users/{userId}/Key2
/users/{userId}/Section/Key3

I cannot find any method to remove all keys starting with: /users/{userId}

How do you remove more than one item from the IDistributedCache at a time?

Pieter
  • 4,721
  • 6
  • 19
  • 18
  • For anyone wondering I ended up doing so by running a SQL delete function on the cache table using a query like this: DELETE FROM [dbo].[cache] Where Key LIKE '/users/{userId}%' – Pieter Sep 27 '18 at 06:17

1 Answers1

0

Removing via SQL statement is not a good solution because the webapp process performs some kind of lock. For example, I had to manually stop after three minutes and half the following simple query Delete from SqlSession with only two records.

So I ended up this way: I retrieve data with a simple query like

Select Id from SqlSession where Id like 'MyIdGroup%'

or with Entity framework

 var cacheElementsToDelete = await _dbContext.SQLSessions
     .Where(a => a.Id.StartsWith("MyIdGroup"))
     .ToListAsync();

Then I use the method of the IDistributedCache to remove each item

 foreach (var item in cacheElementsToDelete)
 {
     await _cache.RemoveAsync(item.Id);
 }    
gehbiszumeis
  • 3,525
  • 4
  • 24
  • 41