如何缓存 IQueryable 对象?
我有这个方法,它返回“UserStatus”表中所有行的 Linq-to-SQL 查询:
public IQueryable<BLL.Entity.UserStatus> GetAll()
{
var query = from e in _SelectDataContext.UserStatus
select new BLL.Entity.UserStatus
{
UserStatusId = e.UserStatusId,
Enum = e.Enum,
Name = e.Name
};
return query;
}
它只是一个几乎不会更改的查找表,因此我想缓存结果。 我可以将其转换为 List<>
并缓存它,但我更愿意返回一个 IQueryable 对象,因为类中的其他方法依赖于此。 有人可以帮忙吗? 谢谢。
I've got this method that returns a Linq-to-SQL query for all the rows in a 'UserStatus' table:
public IQueryable<BLL.Entity.UserStatus> GetAll()
{
var query = from e in _SelectDataContext.UserStatus
select new BLL.Entity.UserStatus
{
UserStatusId = e.UserStatusId,
Enum = e.Enum,
Name = e.Name
};
return query;
}
It's just a look-up table that will hardly ever change so I'd like to cache the results. I can convert it to a List<>
and cache that, but I'd prefer to return an IQueryable object as other methods in the class depend on that. Can anyone help? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
query.ToList().AsQueryable()
可以成为您的解决方案吗? 当然不是最好的。could
query.ToList().AsQueryable()
be a solution for you? not the best one sure.你实际上不能这样做——Querable 更像是一个指针而不是数据。 如果您正在缓存,则您正在缓存数据,因此您需要加载数据。 Yapiskan 有正确的想法——缓存结果 ToList() 并将其返回到 AsQueryable()。
请注意,缓存列表不会有 DataContext,因此您的查询选项将仅限于列表中加载的数据。
You can't really do this--the Querable is more a pointer than the data. If you are caching, you are caching data, so you need to have the data loaded. Yapiskan has the right idea--cache the resulting ToList() and bring it back to AsQueryable().
Do note that the cached list won't have a DataContext so your query options will be limited to data loaded in the list.
我不得不问你实际上想要缓存什么? 查询还是结果?
如果是结果,那么上面的建议是有意义的,但是如果您想缓存查询以供以后使用,那么我可以建议使用 CompiledQuery 然后将其存储在某个地方...
这是一篇关于 CompiledQuery 以及如何使用它。
同样,这完全取决于您是否希望执行查询......
I would have to ask what you are actually wanting to cache? The query or the results?
If its the results then the suggestions above make sense, but if you are wanting to cache the query for later use then may I suggest using CompiledQuery and then storing that somewhere...
Here is an article about CompiledQuery and how to use it.
Again it all depends on whether you want the the query to have been executed or not...
查看企业库缓存应用程序块。 这是一个非常好的通用缓存架构。
Take a look at the Enterprise Library caching application block. It is a very good general purpose caching architecture.