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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With