Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext data caching in entity framework

I am trying to cache an entity using HttpContext caching. My code in service layer is as follows

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

and using in client like this:

 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.

While getting the item it is working fine. But when i try to save the item after updating it getting this error:

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

I understand this is due to retrieving and updating using different DbContexts. When using without caching its working fine. Is there any better other methods to do caching in entity framework ?

like image 594
Mintu Anil Avatar asked Nov 02 '22 14:11

Mintu Anil


1 Answers

Try to attach cached product to current context:

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

Also if you are using Asp.Net MVC then consider to use output caching to cache content returned by controller action.

like image 122
Sergey Berezovskiy Avatar answered Nov 08 '22 08:11

Sergey Berezovskiy