2017-05-18 88 views
0

需要一些帮助。使用DotNet核心尝试使用IDistributedCache从Redis保存和检索对象的JSON数组。下面是我用于存储和Redis的缓存中读取代码dotnet core以RedIs存储对象

public void Save(string key, object content, int duration) 
    { 
     string s; 
     if (content is string) 
     { 
      s = (string)content; 
     } 
     else 
     { 
      s = JsonConvert.SerializeObject(content); 
     } 

     duration = duration <= 0 ? DefaultCacheDuration : duration; 
     Cache.Set(key, Encoding.UTF8.GetBytes(s), new DistributedCacheEntryOptions() 
     { 
      AbsoluteExpiration = DateTime.Now + TimeSpan.FromSeconds(duration) 
     }); 
    } 

public T Get<T>(string key) where T : class 
    { 
     var c = Cache.Get(key); 
     if (c == null) 
     { 
      return null; 
     } 

     var str = Encoding.UTF8.GetString(c); 
     if (typeof(T) == typeof(string)) 
     { 
      return str as T; 
     } 

     return JsonConvert.DeserializeObject<T>(str); 
    } 

,我想存储的对象是

在我的商务逻辑,现在的储蓄对象这样

public IQueryable<RuleLoadCollection_Result> GetRuleLibrary() 
    { 
     var result = _dbClient.GetRuleLibrary(); 
     _cache.Save("TestKey", result); 
     return result; 
    } 

这里的输出是一个对象数组。

[{"ruleId":1,"ruleName":"a1"}] 

我应该写什么代码才能从缓存中返回相同的对象数组?我尝试了几个选项,其中大多数给出了编译或运行时错误。在浏览之后,我在下面尝试,它工作,但它只给出数组的第一个元素。

public RuleLoadCollection_Result GetRuleLibraryFromCache() 
    { 
     return (_cache.Get<List<RuleLoadCollection_Result>>("TestKey").First()); 
    } 

输出,这是

{"ruleId":1,"ruleName":"a1"} 

我明白为什么,但我应该写JSON数组什么C#回到我得救了吗?

下面的代码使运行时错误

public IQueryable<RuleLoadCollection_Result> GetRuleLibraryFromCache() 
    { 
     return (_cache.Get<IQueryable<RuleLoadCollection_Result>>("TestKey")); 
    } 

运行时错误是

"Cannot create and populate list type System.Linq.IQueryable`1[RuleLoadCollection_Result]. Path '', line 1, position 1." 

请帮助。

谢谢。

回答

0

这工作。

public IQueryable<RuleLoadCollection_Result> GetRuleLibraryFromCache() 
    { 
     var result = _cache.Get<IEnumerable<RuleLoadCollection_Result>>("TestKey").AsQueryable(); 
     return result; 
    } 
相关问题