4

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.

Nick
  • 5,616
  • 10
  • 52
  • 72
  • Problem with that is you will have to rebind it to the datacontext later if you want to use it to join another query. That is unless you want the joins or filters ran in memory. – Matthew Whited Jun 17 '09 at 17:19

4 Answers4

7

could query.ToList().AsQueryable() be a solution for you? not the best one sure.

Ali Ersöz
  • 15,860
  • 11
  • 50
  • 64
  • Wasn't aware of the AsQueryable() method. I'm thinking I'll probably end up adding an additional 'List<>' method instead, but this answers the question, thanks. – Nick Jun 17 '09 at 20:40
  • public IQueryable> GetAllCountries(int? primaryCategoryId, int? secondaryCategoryId) { var key = MakeMedia.CustomClasses.Constants.Persistance.PersistanceKeys.AllCountries + primaryCategoryId + secondaryCategoryId; var countries = CacheManager.Get>>(key); if (countries == null) CacheManager.Insert(key, _repository.GetAllCountries(primaryCategoryId, secondaryCategoryId).ToList()); return CacheManager.Get>>(key).AsQueryable(); } – CountZero Jan 07 '11 at 16:22
4

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.

Wyatt Barnett
  • 15,573
  • 3
  • 34
  • 53
2

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...

bytebender
  • 7,371
  • 2
  • 31
  • 54
0

Take a look at the Enterprise Library caching application block. It is a very good general purpose caching architecture.

JP Alioto
  • 44,864
  • 6
  • 88
  • 112