【问题标题】:Typecasting of Azure cache object is always nullAzure 缓存对象的类型转换始终为 null
【发布时间】:2013-07-23 19:39:48
【问题描述】:

这很奇怪,因为无法将 DataCacheItem 投射到列表集合。

我正在从数据库中提取值并将其存储到缓存中,但如果我要求缓存使用 TypeCast 返回数据,那么它拒绝这样做。

Cannot cast 'isValueInCache' (which has an actual type of     
'Microsoft.ApplicationServer.Caching.DataCacheItem') to      
'System.Collections.Generic.List<MMD.Data.HumanGender>'


//Setting Value in Cache Object
var isValueInCache = BaseCache.Instance().RetrieveCacheValue("allGenders");

//TypeCasting of Data
var isSeariled = isValueInCache == null ? 
Newtonsoft.Json.JsonConvert.DeserializeObject(proxy.GetAllGenders(), 
typeof(List<HumanGender>)) as List<HumanGender>
: isValueInCache as List<HumanGender>;

我还没有发现为什么它不能将Object 转换为List&lt;T&gt;。我似乎只在这里工作,以JSON 格式投射对象,按键拉动并创建List Object

更新 1:

这种情况不仅适用于列表,还适用于从缓存中检索到的任何实体对象。

更新 2:

也不使用 DTO。

仍在寻找解决办法。

【问题讨论】:

    标签: c#-4.0 azure collections entity-framework-5 azure-caching


    【解决方案1】:

    你不应该使用数据缓存项的 value 属性吗?

    目前不在 Visual Studio 后面,所以我在没有编译器的情况下编写。

    var isValueInCache = BaseCache.Instance().RetrieveCacheValue("allGenders") as DataCacheItem;
    
    //TypeCasting of Data
    var isSeariled = isValueInCache == null ? 
    Newtonsoft.Json.JsonConvert.DeserializeObject(proxy.GetAllGenders(), 
    typeof(List<HumanGender>)) as List<HumanGender>
    : isValueInCache.Value as List<HumanGender>;
    

    编辑:

    我认为你的 BaseCache 的 RetrieveCacheValue 方法返回了错误的类型。

    【讨论】:

    • 技术上RetrieveCacheValue返回一个对象,而value属性也返回这个对象。所以它的值相同。
    • 同意你的观点。微软在这方面的文档不足。
    【解决方案2】:

    此代码片段将从 Windows Azure 缓存中检索对象(如果存在),并将其存储在缓存中(如果不存在):

    DataCacheFactory cacheFactory = new DataCacheFactory();
    cache = cacheFactory.GetCache("MyCache");
    List<HumanGender> humanGenderList = cache.Get("allGenders") as List<HumanGender>;
    if (humanGenderList == null)
    {
        // "allGenders" not in cache. Obtain it from specified data source and add it.
        humanGenderList = Newtonsoft.Json.JsonConvert.DeserializeObject(proxy.GetAllGenders(), 
            typeof(List<HumanGender>)) as List<HumanGender>;
        cache.Put("allGenders", humanGenderList);
    }
    

    有关详细信息,请参阅How to Use Windows Azure CachingHow to: Use Windows Azure CachingBuilding Windows Azure Cloud Services with Cache Service

    【讨论】:

      猜你喜欢
      • 2014-01-17
      • 2023-03-22
      • 2013-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-19
      相关资源
      最近更新 更多