title: Entity Framework and Unit of Work
body: <p>I am using EF/Repository/Unit of Work, but I am having a hard time understanding some details. Inside the UnitOfWork, I create a new EF DbContext (EmmaContext), but look at inside the repository, I cast it which I know is wrong, how do I get the context inside the repo correctly? Maybe I am totally on the wrong path?</p>
  
  <p>Here is my UnitOfWork:</p>
  
  <pre><code>//Interface
  public interface IUnitOfWork : IDisposable
  {
      void Commit();
  }
  
  //Implementation
  public class UnitOfWork : IUnitOfWork
  {
      #region Fields/Properties
      private bool isDisposed = false;
      public EmmaContext Context { get; set; }
      #endregion
  
      #region Constructor(s)
      public UnitOfWork()
      {
          this.Context = new EmmaContext();
      }
      #endregion
  
      #region Methods
      public void Commit()
      {
          this.Context.SaveChanges();
      }
  
      public void Dispose()
      {
          if (!isDisposed)
              Dispose(true);
          GC.SuppressFinalize(this);
      }
  
      private void Dispose(bool disposing)
      {
          isDisposed = true;
          if (disposing)
          {
              if (this.Context != null)
                  this.Context.Dispose();
          }
      }
      #endregion
  }
  </code></pre>
  
  <p>Here is the repository:</p>
  
  <pre><code>//Interface
  public interface IRepository&lt;TEntity&gt; where TEntity : class
  {
      IQueryable&lt;TEntity&gt; Query();
      void Add(TEntity entity);
      void Attach(TEntity entity);
      void Delete(TEntity entity);
      void Save(TEntity entity);
  }
  
  //Implementation
  public abstract class RepositoryBase&lt;TEntity&gt; : IRepository&lt;TEntity&gt; where TEntity : class
  {
      #region Fields/Properties
      protected EmmaContext context;
      protected DbSet&lt;TEntity&gt; dbSet;
      #endregion
  
      #region Constructor(s)
      public RepositoryBase(IUnitOfWork unitOfWork)
      {
          this.context = ((UnitOfWork)unitOfWork).Context;
          this.dbSet = context.Set&lt;TEntity&gt;();
      }
      #endregion
  
      #region Methods
      public void Add(TEntity entity)
      {
          dbSet.Add(entity);
      }
  
      public void Attach(TEntity entity)
      {
          dbSet.Attach(entity);
      }
  
      public void Delete(TEntity entity)
      {
          dbSet.Remove(entity);
      }
  
      public IQueryable&lt;TEntity&gt; Query()
      {
          return dbSet.AsQueryable();
      }
  
      public void Save(TEntity entity)
      {
          Attach(entity);
          context.MarkModified(entity);
      }
      #endregion
  }
  </code></pre>