实体框架 - 数据缓存独立实体的策略

时间:2013-03-20 15:43:15

标签: c# entity-framework caching entity-framework-4

我决定在我的域服务层上添加一个缓存层,以提高我正在使用的系统的性能。

我之前并没有真正使用缓存,我见过的大多数例子都非常简单。我确定我正在处理的问题是一个熟悉的问题,但我还没有找到任何帮助过我的问题。

简而言之,问题如下:如果我缓存了一个与其他缓存实体有关系的实体,那么确保缓存在更改时始终是最新的最佳方法是什么?任何一位?请注意,从存储库中提取实体时,这些实体将与其数据上下文分离。

这是一个简单的例子:

域对象:

public class Product
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int SpecID { get; set; }
    public ProductSpec Spec { get; set; }
}

public class ProductSpec
{
    public int ID { get; set; }
    public string Name { get; set; }
    public IList<Product> Products { get; set; }
    public IList<ProductSpecDrawing> Drawings { get; set; }
}

public class ProductSpecDrawing
{
    public int ID { get; set; }
    public int ProductSpecID { get; set; }
    public string Name { get; set; }
    public string FileName { get; set; }
    public ProductSpec Spec { get; set; }
    public IList<ProductSpecDrawingRevision> Revisions { get; set; }
}

我的缓存服务的Getter方法:

public override ProductSpec GetProductSpec(int productSpecID)
{
   ProductSpec cachedSpec = cacheStorage.Retrieve("productSpec" + productSpecID);
   if(cachedSpec == null)
   {
       cachedSpec = base.GetProductSpec(productSpecID); //repository lookup
       cacheStorage.Store("productSpec" + productSpecID, cachedSpec);
   }
   return cachedSpec;
}

类似方法缓存/检索Product,ProductSpecDrawing等

现在,问题是:如果对ProductSpecDrawing对象进行了更新,例如,我需要查找并更新可能引用此对象的任何其他对象的缓存,否则我可能会查看过时的数据。这看起来像这样:

public override void RemoveProductSpecDrawing(int specDrawingID)
{
    ProductSpecDrawing drawingToRemove = cacheStorage.Retrieve<ProductSpecDrawing>("specDrawing" + specDrawingID);
    base.RemoveProductSpecDrawing(specDrawingID);
    cacheStorage.Remove(drawingToRemove);

    //have to update productSpec collection because we removed a drawing
    cacheStorage.Store("spec" + drawingToRemove.ProductSpec.ID, base.GetProductSpec(drawingToRemove.ProductSpec.ID);
}

我认为我的缓存每个实体的方式存在问题,原因有两个:数据变得陈旧(特别是当域变大时)有很多机会,并且需要刷新可能的许多缓存对象在单次更新后,它似乎会否定任何性能提升(除非用户只查看内容而不是编辑它们)。

0 个答案:

没有答案
相关问题