Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体框架中的HttpContext数据缓存_C#_Entity Framework_Caching - Fatal编程技术网

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

C# 实体框架中的HttpContext数据缓存,c#,entity-framework,caching,C#,Entity Framework,Caching,我正在尝试使用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) {

我正在尝试使用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.
虽然得到的项目,它是工作正常。但当我在更新项目后尝试保存该项目时,出现以下错误:

实体对象不能由的多个实例引用 IEntityChangeTracker


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

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

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.NETMVC,则考虑使用缓存控制器动作返回的内容。

我已经尝试过。在更新调用发生之前,它显示了相同的错误。ie第一次调用填充控件。@MintuAnil抱歉,刚刚验证-缓存可以与上面的代码配合使用此建议使用
Attach(Entity)
为我指明了正确的方向。最后的诀窍是在初始查询中添加
.AsNoTracking
。在我的例子中(VB.Net):
DbContext.Instance.ABC.Include(Function(u)u.XYZ).AsNoTracking.ToList