4
我想缓存使用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更新。使用时没有缓存它的工作正常。有没有更好的其他方法在实体框架中进行缓存?如果您使用的Asp.Net MVC再考虑使用output caching来缓存控制器动作返回的内容
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;
}
另外:
我已经试过这个。它甚至在更新调用发生之前显示相同的错误。即第一次调用控件。 –
@MintuAnil对不起,刚刚验证 - 缓存工作正常与上面的代码 –