【发布时间】:2017-08-01 15:51:33
【问题描述】:
我有一个基于 ASP.NET MVC5 框架和 Entity 6 框架编写的应用程序。
通常,缓存关系没有帮助。但是,我有一个案例,相关数据永远不会改变,但父母会改变。我正在寻找一种仅缓存关系的方法,这样我就不必在每次加载页面时都进行硬读。
我有以下两个类
public class Item
{
public string Id { get; set; }
public string Name { get; set; }
public int CategoryId { get; set; }
public decimal Rate { get; set; }
...
...
public virtual ICollection<ItemRecord> Records { get; set; }
}
public class ItemRecord
{
public string Id { get; set; }
public string Title { get; set; }
public decimal Description { get; set; }
public decimal Amount { get; set; }
[ForeignKey("Item")]
public int ItemId { get; set; }
...
...
public virtual ItemRecord Item { get; set; }
}
在控制器中的 Index 操作中,我可以使用以下 linq 语句获取数据。
public ActionResult Index(int? id)
{
if(id.HasValue)
{
var items = Context.Items.Where(item => item.CategoryId == id.Value)
.Include(x => x.Records)
.ToList();
}
....
}
由于Item 模型一直在变化,我不想缓存它。但是,我想缓存 Records 关系中的所有数据,因为它永远不会改变并且它是大型数据集。
问题
如何在上面的示例中缓存 Records 关系?
我尝试使用OutputCache 属性来缓存这样的关系
public class Item
{
public string Id { get; set; }
public string Name { get; set; }
public int CategoryId { get; set; }
public decimal Rate { get; set; }
...
...
[OutputCache(Duration = 3600, VaryByParam = "CategoryId", Location = OutputCacheLocation.Server)]
public virtual ICollection<ItemRecord> Records { get; set; }
}
你可以看出这不起作用,这是我得到的错误
属性“OutputCache”在此声明类型上无效。这是 仅对“类、方法”声明有效。
显然OutputCache 用于缓存类而不是实体关系。
【问题讨论】:
标签: c# asp.net entity-framework caching asp.net-mvc-5