Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

News

My Friends

My Links

Permanent Posts

Portuguese Communities

March 2012 - Posts

Entity Framework Code First: Get Entities From Local Cache or the Database

Entity Framework Code First makes it very easy to access local (first level) cache: you just access the DbSet<T>.Local property. This way, no query is sent to the database, only performed in already loaded entities.

If you want to first search local cache, then the database, if no entries are found, you can use this extension method:

   1: public static class DbContextExtensions
   2: {
   3:     public static IQueryable<T> LocalOrDatabase<T>(this DbContext context, Expression<Func<T, Boolean>> expression) where T : class
   4:     {
   5:         IEnumerable<T> localResults = context.Set<T>().Local.Where(expression.Compile());
   6:  
   7:         if (localResults.Any() == true)
   8:         {
   9:             return (localResults.AsQueryable());
  10:         }
  11:  
  12:         IQueryable<T> databaseResults = context.Set<T>().Where(expression);
  13:  
  14:         return (databaseResults);
  15:     }
  16: }
Creating a Control From its Markup Representation

No words, just code!

   1: public static T CreateControlFromMarkup<T>(String markup) where T: Control
   2: {
   3:     StringBuilder builder = new StringBuilder();
   4:     TemplateControl page = HttpContext.Current.Handler as TemplateControl;
   5:     Int32 start = markup.IndexOf('<');
   6:     Int32 end = markup.IndexOf(':', start);
   7:     String tagPrefix = markup.Substring(start + 1, end - start - 1);
   8:  
   9:     foreach (String @namespace in typeof(T).Assembly.GetExportedTypes().Select(x => x.Namespace).OrderBy(x => x).Distinct())
  10:     {
  11:         builder.AppendFormat("<%@ Register Assembly=\"{0}\" Namespace=\"{1}\" TagPrefix=\"{2}\" %>\n", typeof(T).Assembly.FullName, @namespace, tagPrefix);
  12:     }
  13:  
  14:     builder.Append(markup);
  15:  
  16:     Control parentControl = page.ParseControl(builder.ToString());
  17:     T control = parentControl.Controls[0] as T;
  18:  
  19:     return (control);
  20: }
More Posts