VahidN / EFSecondLevelCache.Core

Entity Framework Core Second Level Caching Library
Apache License 2.0
326 stars 50 forks source link

Unable to cast object of type 'EFSecondLevelCache.Core.Contracts.EFCacheKey' to type ** #5

Closed fishen closed 7 years ago

fishen commented 7 years ago

I used redis for cahce provider in my app, when the first time to fetch data from db, it will return a empty result and cache the result to the redis, but i found the cached data is incorrent, the cached value is '{"CacheDependencies": []}' and the value type is 'EFSecondLevelCache.Core.Contracts.EFCacheKey, EFSecondLevelCache.Core, Version=1.0.3.0, Culture=neutral, PublicKeyToken=null' , so it willl throw a castexception when attemp read again.

Code: var entity=context.Set<ProductCategorie>().Where(m=>!m.Deleted).Cacheable().FirstOrDefault();

Error: System.InvalidCastException:“Unable to cast object of type 'EFSecondLevelCache.Core.Contracts.EFCacheKey' to type 'Jazea.Chain.Domain.Entity.ProductCategorie'.”

fishen commented 7 years ago

It works when use ToList() or Count().

public static void AddCache(IServiceCollection services)
{
    var provider = services.BuildServiceProvider();
    var config = provider.GetService<IConfigurationRoot>();
    var redisConnStr = config.GetValue<string>("RedisConnetionString");
    services.AddEFSecondLevelCache();
    services.AddSingleton(typeof(ICacheManager<>), typeof(BaseCacheManager<>));
    var jss = new JsonSerializerSettings()
    {
        NullValueHandling = NullValueHandling.Ignore,
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
    };
    services.AddSingleton<ICacheManagerConfiguration>(
        new CacheManager.Core.ConfigurationBuilder()
            .WithJsonSerializer(jss, jss)
            .WithRedisConfiguration("Redis", redisConnStr)
            .WithRedisCacheHandle("Redis")
            .WithExpiration(ExpirationMode.None, TimeSpan.FromHours(1))
            .Build()
    );
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    app.UseEFSecondLevelCache();
    app.Map("/api", c => c.UseMvc());
}
fishen commented 7 years ago

1 default

fishen commented 7 years ago

Because i set NullValueHandling = NullValueHandling.Ignore, so the cached value is incomplete. The complate info is :

{
  "Key": null,
  "KeyHash": null,
  "CacheDependencies": []
}

It will throw InvalidCastException while reading the cahed value .

VahidN commented 7 years ago

redis01

redis02

VahidN commented 7 years ago

It's fixed via https://github.com/VahidN/EFSecondLevelCache.Core/commit/15839e39b10ef581139fe558a64d0adf85a8c074 (Improved null object detection).

PM> update-package
lock[bot] commented 4 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related problems.