title: How do I cache lookup data with Entity Framework 6
body: <p>I'm learning my way around EF, and I know caching is faster than a round trip to the DB for things like state, country, etc. But I'm not sure how to implement it. I was looking at this post (<a href="http://weblogs.asp.net/ricardoperes/entity-framework-code-first-get-entities-from-local-cache-or-the-database" rel="nofollow">entities from local cache</a>) that mentioned an extension, but is there something built in I should leverage?</p>
  
  <p>I'd like to have a function like this that wouldn't have to go to the db every time:</p>
  
  <pre><code>public static int GetCountryId(string countryCode = "US")
  {
      if (countryCode == string.Empty)
          countryCode = "US"; // Assume US
      return db.Country.Where
          (
              p =&gt; p.CountryCode == countryCode
          ).Select(p =&gt; p.CountryId).First();
  }
  </code></pre>
  
  <p><strong><em>Updated:</em></strong></p>
  
  <p>I'm now thinking about a GetCached function that would use generics to hold some lookup lists in memory. Somthing like this:</p>
  
  <pre><code>public class Lookups
  {
      private static MkpContext db = new MkpContext();
  
      public static IEnumerable GetCached(CachedLists list)
      {
          ObjectCache cache = MemoryCache.Default;
          var listOut = cache[list.ToString()] as IEnumerable;
          if (listOut != null) return listOut;
  
          switch (list)
          {
              case CachedLists.Countries:
                  cache.Set
                  (
                      list.ToString(),
                      db.Country.ToList(),
                      new DateTimeOffset(DateTime.Now,new TimeSpan(1,0,0,0))
                  );
                  break;
              default:
                  return null;
          }
  
          listOut = cache[list.ToString()] as IEnumerable;
          return listOut;
      }
  
  }    
  
  public enum CachedLists
  {
      Countries,
  }
  </code></pre>
  
  <p>But the above solution would leave me with an un-typed Enumerable. I'd love to be able to specify the types somehow, or better yet, do some sort of extension.</p>