Reputation: 56
I am using this package Microsoft.Extensions.Caching.Redis
.
What is the way to pass tModel
to set and get from cache.
public class TestModel
{
public int test1 { get; set; }
public string test2 { get; set; }
}
var tModel = new TestModel();
tModel.test1 = 1;
tModel.test2 = "abc";
_distributedCache.Set("model", tModel);
Upvotes: 0
Views: 2096
Reputation: 46591
I would serialize the data to JSON and persist it as a string:
using Newtonsoft.Json;
// ...
// Set
var jsonData = JsonConvert.SerializeObject(tModel);
_distributedCache.SetString("model", jsonData);
// Get
var jsonData = _distributedCache.GetString("model");
var tModel = JsonConvert.DeserializeObject<TestModel>(jsonData);
Notice I used the GetString
and SetString
extension methods here, rather than the low-level Get
and Set
method which takes and returns bytes. There are also async methods available.
Upvotes: 3