实体框架中的HttpContext数据缓存

Min*_*nil 5 c# caching entity-framework

我正在尝试使用 HttpContext 缓存来缓存一个实体。我在服务层的代码如下

public Product GetById(long id)
{
  Product product;
  string storageKey = string.Format("products_{0}",id.ToString());
  product = (Product)HttpContext.Current.Cache.Get(storageKey);
  if (product == null)
  {
     product = _productContext.Products.Find(id);
      HttpContext.Current.Cache.Insert(storageKey, product);
  }     
  return product;
}
Run Code Online (Sandbox Code Playgroud)

并像这样在客户端使用:

 ProductService productServices = new ProductService(_dbContext);
 var product = productServices.GetById(id);
  //... Populating controls

 //On Update button click
  ProductService productServices = new ProductService(_dbContext);
  var product = productServices.GetById(id);
  //Updating values of product and saveChanges.
Run Code Online (Sandbox Code Playgroud)

在获得物品时,它工作正常。但是当我在更新后尝试保存该项目时出现此错误:

一个实体对象不能被 IEntityChangeTracker 的多个实例引用。

我知道这是由于使用不同的 DbContext 进行检索和更新。使用时不缓存它的工作正常。在实体框架中是否有更好的其他方法进行缓存?

Ser*_*kiy 2

尝试将缓存的产品附加到当前上下文:

public Product GetById(long id)
{
   Product product;
   string storageKey = string.Format("products_{0}",id.ToString());
   product = (Product)HttpContext.Current.Cache.Get(storageKey);
   if (product == null)
   {
      product = _productContext.Products.Find(id);
      HttpContext.Current.Cache.Insert(storageKey, product);
   }
   else
   {
       _productContext.Products.Attach(product);
   }
   return product;
}
Run Code Online (Sandbox Code Playgroud)

另外,如果您使用 Asp.Net MVC,请考虑使用输出缓存来缓存控制器操作返回的内容。