Search code examples
c#-4.0azurecollectionsentity-framework-5azure-caching

Typecasting of Azure cache object is always null


That's very weird as unable to cast a DataCacheItem to List Collection.

i am pulling the value from database and Storing it to in Cache but if i ask cache to return the data with TypeCast, then it refused to do that.

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>;

i haven't found out why it not able to cast the Object to List<T>. only Work around here i seem , Cast object in JSON format, pull by Key and Create List Object.

Update 1:

this case is with not only List but also any Entity Object which is Retrieved form the Cache.

Update 2:

Not Working with DTO also.

Still looking in work around in this.


Solution

  • Shouldn't you use the value property of the datacache item?

    Currently not behind a Visual Studio so i'm writing this without a compiler.

    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>;
    

    Edit:

    I think the RetrieveCacheValue method of your BaseCache returns the wrong type.