title: Entity framework with generic repository and Unit of Work store showing old data
body: <p>I'm busy working on a custom made CMS and website. The CMS and website both share the same datalayer and the datalayer is using an generic repository pattern combined with a Unit of Work store.</p>
  
  <p>The problem occurs when i'm viewing a page of the website having a simple line of text on it. This line of text is edited in the CMS. When editing this line of text and saving it in the CMS I see the entity being modified and I also see the changes in the database.
  However after changing this small piece of text through the CMS and then refreshing the website page i'm still being presented with the old text.</p>
  
  <p>The only way for me to be able to show the new, changed text is to restart IIS of add an space in the web.config and save it so the application pool is recycled. So it seems to me it has something to do with the caching of the entity context.</p>
  
  <p>Below is my generic repository code and my unit-of-work-store code. I think the problem is in one of these and that somehow the cache of the entity context needs to be renewed or that entities needs to be reloaded. What can I possibly do to solve this issue?</p>
  
  <p><em>Info: The Unit of work is based on <a href="http://samscode.com/index.php/2009/12/making-entity-framework-v1-work-part-1-datacontext-lifetime-management/" rel="nofollow">this</a> article. And the website and CMS are running in an seperate IIS application pool on my local development pc</em></p>
  
  <p><strong>GenericRepository.cs</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Data.Entity;
  using System.Data.Entity.Validation;
  using System.Data.Objects;
  using System.IO;
  using System.Linq;
  using System.Linq.Expressions;
  using CORE.Model;
  using CORE.RepositoryInterfaces;
  
  namespace CORE.Repositories
  {
  
      public class GenericRepository&lt;TEntity&gt; : IGenericRepository&lt;TEntity&gt; where TEntity : class
      {
          #region Implementation of IRepository&lt;TEntity&gt;
  
          //private readonly myContext _context;
          private readonly DbSet&lt;TEntity&gt; _dbSet;
  
          public GenericRepository()
          {
              //_context = new myContext();
              //_dbSet = _context.Set&lt;TEntity&gt;();
  
              _dbSet = DataLayer.Instance.Context.Set&lt;TEntity&gt;();
          }
  
          /// &lt;summary&gt;
          /// Inserts a new object into the database
          /// &lt;/summary&gt;
          /// &lt;param name="entity"&gt;The entity to insert&lt;/param&gt;
          public void Insert(TEntity entity)
          {
              _dbSet.Add(entity);
          }
  
          /// &lt;summary&gt;
          /// Deletes the specified entity from the database
          /// &lt;/summary&gt;
          /// &lt;param name="entity"&gt;The object to delete&lt;/param&gt;
          public void Delete(TEntity entity)
          {
              if (DataLayer.Instance.Context.Entry(entity).State == System.Data.EntityState.Detached)
              {
                  _dbSet.Attach(entity);
              }
  
              _dbSet.Remove(entity);
          }
  
          /// &lt;summary&gt;
          /// Saves all pending chances to the database
          /// &lt;/summary&gt;
          public void Save()
          {
              try
              {
                  DataLayer.Instance.Context.SaveChanges();
              }
              catch (DbEntityValidationException e)
              {
                  //foreach (var eve in e.EntityValidationErrors)
                  //{
                  //    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                  //        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                  //    foreach (var ve in eve.ValidationErrors)
                  //    {
                  //        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                  //            ve.PropertyName, ve.ErrorMessage);
                  //    }
                  //}
                  //throw;
  
                  //Log all errors to an temp file.
                  //TODO: Implement NLog
                  var outputLines = new List&lt;string&gt;();
                  foreach (var eve in e.EntityValidationErrors)
                  {
                      outputLines.Add(string.Format(
                          "{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
                          DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
  
                      foreach (var ve in eve.ValidationErrors)
                      {
                          outputLines.Add(string.Format(
                              "- Property: \"{0}\", Error: \"{1}\"",
                              ve.PropertyName, ve.ErrorMessage));
                      }
                  }
                  File.AppendAllLines(@"c:\temp\errors.txt", outputLines);
  
                  throw;
              }
          }
  
          /// &lt;summary&gt;
          /// Retrieves the first object matching the specified query.
          /// &lt;/summary&gt;
          /// &lt;param name="where"&gt;The where condition to use&lt;/param&gt;
          /// &lt;returns&gt;The first matching object, null of none found&lt;/returns&gt;
          public TEntity First(Expression&lt;Func&lt;TEntity, bool&gt;&gt; @where)
          {
              return _dbSet.FirstOrDefault(where);
          }
  
          /// &lt;summary&gt;
          /// Gets a list of all objects
          /// &lt;/summary&gt;
          /// &lt;returns&gt;An strong typed list of objects&lt;/returns&gt;
          public IEnumerable&lt;TEntity&gt; GetAll()
          {
              return _dbSet.AsEnumerable();
          }
  
          /// &lt;summary&gt;
          /// Returns ans iQueryable of the matching type
          /// &lt;/summary&gt;
          /// &lt;returns&gt;iQueryable&lt;/returns&gt;
          public IQueryable&lt;TEntity&gt; AsQueryable()
          {
              return _dbSet.AsQueryable();
          }
  
          //public void Dispose()
          //{
          //    DataLayer.Instance.Context.Dispose();
          //    GC.SuppressFinalize(this);
          //}
          #endregion
      }
  }
  </code></pre>
  
  <p><strong>UnitOfWorkStore.CS</strong></p>
  
  <pre><code>using System.Runtime.Remoting.Messaging;
  using System.Web;
  
  namespace CORE
  {
      /// &lt;summary&gt;
      /// Utility class for storing objects pertinent to a unit of work.
      /// &lt;/summary&gt;
      public static class UnitOfWorkStore
      {
          /// &lt;summary&gt;
          /// Retrieve an object from this store via unique key.
          /// Will return null if it doesn't exist in the store.
          /// &lt;/summary&gt;
          /// &lt;param name="key"&gt;&lt;/param&gt;
          /// &lt;returns&gt;&lt;/returns&gt;
          public static object GetData(string key)
          {
              if (HttpContext.Current != null)
                  return HttpContext.Current.Items[key];
              return CallContext.GetData(key);
          }
  
  
          /// &lt;summary&gt;
          /// Put an item in this store, by unique key.
          /// &lt;/summary&gt;
          /// &lt;param name="key"&gt;&lt;/param&gt;
          /// &lt;param name="data"&gt;&lt;/param&gt;
          public static void SetData(string key, object data)
          {
              if (HttpContext.Current != null)
                  HttpContext.Current.Items[key] = data;
              else
                  CallContext.SetData(key, data);
          }
  
      }
  }
  </code></pre>
  
  <p><strong>DataLayer.cs</strong></p>
  
  <pre><code>using System;
  using CORE.Model;
  
  namespace CORE
  {
      /// &lt;summary&gt;
      /// This is the data access layer management class.
      /// See 
      /// &lt;/summary&gt;
      public sealed class DataLayer : IDisposable
      {
          /// &lt;summary&gt;
          /// This is our key to store an instance of this class in the &lt;see cref="UnitOfWorkStore" /&gt;.
          /// This is used in the &lt;see cref="Instance" /&gt; property.
          /// &lt;/summary&gt;
          private const string UowInstanceKey = "MyContext_Instance";
  
          /// &lt;summary&gt;
          /// This is used for thread-safety when creating the instance of this class to be stored in
          /// the UnitOfWorkStore.
          /// &lt;/summary&gt;
          private static readonly object SObjSync = new object();
  
          // The DataContext object
          private readonly MyContext _context;
  
  
  
          // ********************************************************************************
          // *** Constructor(s) *************************************************************
          // ********************************************************************************
  
          /// &lt;summary&gt;
          /// Default constructor.  Creates a new MyEntities DataContext object.
          /// This is hidden (private) because the instance creation is managed as a "unit-of-work", via the
          /// &lt;see cref="Instance" /&gt; property.
          /// &lt;/summary&gt;
          private DataLayer()
          {
              _context = new MyContext();
          }
  
  
  
          // ********************************************************************************
          // *** Public properties **********************************************************
          // ********************************************************************************
  
          /// &lt;summary&gt;
          /// The ObjectContext object that gives us access to our business entities.
          /// Note that this is NOT static.
          /// &lt;/summary&gt;
          public BorloContext Context
          {
              get { return _context; }
          }
  
  
          /// &lt;summary&gt;
          /// This will get the "one-and-only" instance of the DataLayer that exists for the lifetime of the current "unit of work",
          /// which might be the lifetime of the currently running console application, a Request/Response iteration of an asp.net web app,
          /// an async postback to a web service, etc.
          /// 
          /// This will never return null.  If an instance hasn't been created yet, accessing this property will create one (thread-safe).
          /// This uses the &lt;see cref="UnitOfWorkStore" /&gt; class to store the "one-and-only" instance.
          /// 
          /// This is the instance that is used by all of the DAL's partial entity classes, when they need a reference to a MyEntities context
          /// (DataLayer.Instance.Context).
          /// &lt;/summary&gt;
          public static DataLayer Instance
          {
              get
              {
                  object instance = UnitOfWorkStore.GetData(UowInstanceKey);
  
                  // Dirty, non-thread safe check
                  if (instance == null)
                  {
                      lock (SObjSync)
                      {
                          // Thread-safe check, now that we're locked
                          // ReSharper disable ConditionIsAlwaysTrueOrFalse
                          if (instance == null) // Ignore resharper warning that "expression is always true". It's not considering thread-safety.
                          // ReSharper restore ConditionIsAlwaysTrueOrFalse
                          {
                              // Create a new instance of the DataLayer management class, and store it in the UnitOfWorkStore,
                              // using the string literal key defined in this class.
                              instance = new DataLayer();
                              UnitOfWorkStore.SetData(UowInstanceKey, instance);
                          }
                      }
                  }
  
                  return (DataLayer)instance;
              }
          }
  
          public void Dispose()
          {
              _context.Dispose();
              GC.SuppressFinalize(this);
          }
      }
  }
  </code></pre>
  
  <p><strong>UPDATE - 1: Usage of GenericRepository through genericservice</strong></p>
  
  <p><em><strong>The usage in the service of the CMS:</em></strong></p>
  
  <pre><code>private readonly IGenericService&lt;TextBlock&gt; _textBlockService;
  
  public TextBlockController(): base(new GenericService&lt;ComponentType&gt;(), new GenericService&lt;Blog&gt;())
  {
      if (_textBlockService == null)
      {
          _textBlockService = new GenericService&lt;TextBlock&gt;();
      }
  }
  </code></pre>
  
  <p><em><strong>The usage of the service frontend, through an HTML helper</em></strong></p>
  
  <pre><code>public static class RenderEngine
  {
      private static readonly IGenericService&lt;Component&gt; ComponentService;
      private static readonly IGenericService&lt;TextBlock&gt; TextBlockService;
  
      /// &lt;summary&gt;
      /// Constructor for this class.
      /// &lt;/summary&gt;
      static RenderEngine()
      {
          if (ComponentService == null)
          {
              ComponentService = new GenericService&lt;Component&gt;();
          }
          if (TextBlockService == null)
          {
              TextBlockService = new GenericService&lt;TextBlock&gt;();
          }
      }
  
      //Html helper method does something like TekstBlokService.First(/*linq statement*/)
  }
  </code></pre>
  
  <p><em><strong>UPDATE - 2: Added code for genericservice</em></strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Linq.Expressions;
  using System.Text;
  using System.Threading.Tasks;
  using CORE.Repositories;
  using CORE.RepositoryInterfaces;
  using BLL.ServiceInterfaces;
  
  namespace BLL.Services
  {
  
      public class GenericService&lt;T&gt; : IGenericService&lt;T&gt; where T : class
      {
          #region properties
          protected readonly IGenericRepository&lt;T&gt; MyRepository;
          #endregion
  
          #region constructor
          //[Inject]
          public GenericService(IGenericRepository&lt;T&gt; repository)
          {
              MyRepository = repository;
          }
  
          //public GenericService()
          //{
          //    if (Repository == null)
          //    {
          //        Repository = new Repository&lt;T&gt;();
          //    }
  
          //}
  
          ////todo: uitzoeken!
          public GenericService()
              : this(new GenericRepository&lt;T&gt;())
          {
  
          }
  
          #endregion
  
          #region Implementation of IService&lt;T&gt;
  
          /// &lt;summary&gt;
          /// Inserts a new object into the database
          /// &lt;/summary&gt;
          /// &lt;param name="entity"&gt;The entity to insert&lt;/param&gt;
          public void Insert(T entity)
          {
              MyRepository.Insert(entity);
          }
  
          /// &lt;summary&gt;
          /// Retrieves the first object matching the specified query.
          /// &lt;/summary&gt;
          /// &lt;param name="where"&gt;The where condition to use&lt;/param&gt;
          /// &lt;returns&gt;The first matching object, null of none found&lt;/returns&gt;
          public T First(Expression&lt;Func&lt;T, bool&gt;&gt; @where)
          {
              return MyRepository.First(where);
          }
  
          /// &lt;summary&gt;
          /// Gets a list of all objects
          /// &lt;/summary&gt;
          /// &lt;returns&gt;An strong typed list of objects&lt;/returns&gt;
          public IEnumerable&lt;T&gt; GetAll()
          {
              return MyRepository.GetAll();
          }
  
          /// &lt;summary&gt;
          /// Returns ans iQueryable of the matching type
          /// &lt;/summary&gt;
          /// &lt;returns&gt;iQueryable&lt;/returns&gt;
          public IQueryable&lt;T&gt; AsQueryable()
          {
              return MyRepository.AsQueryable();
          }
  
          /// &lt;summary&gt;
          /// Deletes the specified entity from the database
          /// &lt;/summary&gt;
          /// &lt;param name="entity"&gt;The object to delete&lt;/param&gt;
          public void Delete(T entity)
          {
              MyRepository.Delete(entity);
          }
  
          /// &lt;summary&gt;
          /// Saves all pending chances to the database
          /// &lt;/summary&gt;
          public void Save()
          {
              MyRepository.Save();
          }
  
          //protected override void Dispose(bool disposing)
          //{
          //    _movieService.Dispose();
          //    base.Dispose(disposing);
          //}
  
          #endregion
  
          //public void Dispose()
          //{
          //    MyRepository.Dispose();
          //    GC.SuppressFinalize(this);
          //}
      }
  }
  </code></pre>