简体   繁体   English

在实体框架中使用泛型进行缓存

[英]Using generics for caching in the Entity Framework

I am using Cache pattern with Entity Framework and my problem is that for the Azure caching service I need data serialized. 我使用缓存模式与实体框架,我的问题是,对于Azure缓存服务,我需要序列化数据。 Which basically means that I need to call ToList() to be able to data to the cache (see comment in the code to locate correct line). 这基本上意味着我需要调用ToList()才能将数据发送到缓存(请参阅代码中的注释以找到正确的行)。

Entity Framework's data is in the ObjectSet<T> and it's base class is System.Data.Objects.ObjectQuery<TEntity> . Entity Framework的数据位于ObjectSet<T> ,它的基类是System.Data.Objects.ObjectQuery<TEntity> Should I have somehow say in the method definition (RetrieveCachedData) that T is based on that one or how I can access ToList method? 我应该在方法定义(RetrieveCachedData)中以某种方式说T基于那个或我如何访问ToList方法?

protected T RetrieveCachedData<T>(string cacheKey, Func<T> fallbackFunction, CacheItemPolicy cachePolicy) where T : class
{            
    var cache = new AzureCache().GetCache();
    var data = cache.Get(cacheKey) as T;

    if (data != null)
    {
        return data;
    }

    data = fallbackFunction();
    if (data != null)
    {
        // I need to call .ToList() here to be able to add it to the cache
        cache.Add(cacheKey, data); 
    }
    return data;
}

Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM