Skip to content
pwelter34 edited this page May 29, 2012 · 3 revisions

Overview

To cache query results, use the FromCache extension method located in the EntityFramework.Extensions namespace. Below is a sample caching query results. Simply construct the LINQ query as you normally would, then append the FromCache extension.

//query is cached using the default settings
var tasks = db.Tasks
    .Where(t => t.CompleteDate == null)
    .FromCache();

//query result is now cached 300 seconds
var tasks = db.Tasks
    .Where(t => t.AssignedId == myUserId && t.CompleteDate == null)
    .FromCache(CachePolicy.WithDurationExpiration(TimeSpan.FromSeconds(300)));

Cache Tag

The Query Result Cache also supports tagging the cache so you can expire common cache entries by calling Expire on a cache tag.

// cache assigned tasks
var tasks = db.Tasks
    .Where(t => t.AssignedId == myUserId && t.CompleteDate == null)
    .FromCache(tags: new[] { "Task", "Assigned-Task-" + myUserId  });

// some update happened to Task, expire Task tag
CacheManager.Current.Expire("Task");

Provider Support

The CacheManager has support for providers. The default provider uses MemoryCache to store the cache entries. To implement a custom provider, implement ICacheProvider. The custom provider will then need to be registered in the Locator resolver.

// Replace cache provider with Memcached provider
Locator.Current.Register<ICacheProvider>(() => new MemcachedProvider());

Default Cache Policy

When no CachePolicy is set, the CachePolicy.Default is used. You can set the values of CachePolicy.Default on application startup to have default settings.

Clone this wiki locally