微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 实体框架中的HttpContext数据缓存

我正在尝试使用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;
}

并在客户端使用这样:

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.

获得该项目时它工作正常.但是当我在更新后尝试保存该项时会收到此错误

An entity object cannot be referenced by multiple instances of
IEntityChangeTracker.

我理解这是由于使用不同的DbContexts检索和更新.使用时没有缓存其工作正常.有没有更好的其他方法在实体框架中进行缓存?

解决方法

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

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

此外,如果您使用的是Asp.Net MVC,请考虑使用output caching来缓存控制器操作返回的内容.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐