加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 21:56:35 所属栏目:百科 来源:网络整理
导读:我正在尝试使用HttpContext缓存来缓存实体.我在服务层的代码如下 public Product GetById(long id){ Product product; string storageKey = string.Format("products_{0}",id.ToString()); product = (Product)HttpContext.Current.Cache.Get(storageKey); i
我正在尝试使用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来缓存控制器操作返回的内容.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读