ASP.NET CORE use MemoryCache or similar for send copy of Cache

Jan Sršeň

I would like to ask for help.

I would like to use some type of .NET Core Memory Caching for my ASP.NET Core web app.

I try to use MemoryCache (Microsoft.Extensions.Caching.Memory), but I found out then MemoryCache returns a reference to the object, not a copy.

I read this question, but it does not help me a lot Does accessing MemoryCache create a copy?

I load Materialized View (MV) from DB to Cache, and after that, I use this Array for LINQ (Where(w => w.link == 'API link')) to find only rows/Object which I want to use.

For this sorted Array with data that I want to use, I apply some rules where I set it if a row is Active or Not (use that data like Active Filter, default all rows are Active).

The array (in MemoryCache) contains all parameters for all products and after getting API Filter response to find only data which has data from sending API active filter (Active filters set by users on Web Form => filters) and others set as InActive.

Like:

{
"link": "/product_group1/product_group_2",
"pageNo": 1,
"pageSize": 25,
"filters": [
    {
        "name": "money",
        "type": "select",
        "values": [{ "value": "1200" }]
     },
     {
        "name": "rating",
        "type": "range",
        "values": [{ "value": "1.5" }, {"value": "3"}]
     }
 ]
}

Data Array in Cache (orig from DB):

Id  Name    Value   Type    FieldName   Active
24  Rating  4       select  rating      true
24  Rating  1.5     select  rating      true
24  Rating  2       select  rating      true

After apply filters:

Id  Name    Value   Type    FieldName   Active
24  Rating  4       select  rating      false
24  Rating  1.5     select  rating      true
24  Rating  2       select  rating      true

I find in Array at Cache all row which has a filter with name money and value with 1200 and also with a filter with name range where value is between 1.5 and 3 starts of rating.

Always when I call a function that returns me an Array From Cache I want to get the same data as in DB.

Is there any way how return COPY from MemoryCache or is there another way like Class/Interface to use?

Thank you

Jan Sršeň

Simply solution by create DEEP copy by LINQ Select with create new List of Objects with filter ID which I want to looking for:

// Create new empty List
var newList = new List<Obj>();
// Fill list by data from cached list
newList.AddRange(cachedList.Where(w => w.link == 'API link')
                           .Select(s => new Obj(s))
                );

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related