title: Entity Framework and the repository pattern
body: <p>I want to use entity framework to persist domain entites. My Project is setup as follows:-</p>
  
  <ul>
  <li>UI: MVC (Uses Automapper to map between domain entities and view models)</li>
  <li>Domain: Entites, Services, Repository Interfaces</li>
  <li>Repository: Entity Framework (implementing the interfaces from the domain layer). Uses Automapper to map between domain entities and Entity framework objects.</li>
  </ul>
  
  <p>This works well, except when in my service if I do something like validate an item by checking the repository, then performing an update. This fails because Entity Frameworks identity map has seen the item before, and I try and attach it again.</p>
  
  <p>I can work around this issue using code as follows (this would be made more generic)</p>
  
  <pre><code>        public void Update(Domain.Entities.Book entity)
      {
          Book newBook = _mapper.Map&lt;Domain.Entities.Book, Book&gt;(entity);
          ObjectStateEntry cacheEntry;
          if (_dataContext.ObjectStateManager.TryGetObjectStateEntry(_dataContext.CreateEntityKey("Books",newBook), out cacheEntry))
          {
              _dataContext.Books.ApplyCurrentValues(newBook);
          }
          else
          {
              _dataContext.Books.Attach(newBook);
              _dataContext.ObjectStateManager.ChangeObjectState(newBook, EntityState.Modified);
          }
          _dataContext.SaveChanges();
      }
  </code></pre>
  
  <p>The problem is I find my self having to write the same sort of code for deletions</p>
  
  <pre><code>        public void Delete(Domain.Entities.Book entity)
      {
          Book newBook = _mapper.Map&lt;Domain.Entities.Book, Book&gt;(entity);
          ObjectStateEntry cacheEntry;
          if (_dataContext.ObjectStateManager.TryGetObjectStateEntry(_dataContext.CreateEntityKey("Books", newBook), out cacheEntry))
          {
              _dataContext.ObjectStateManager.ChangeObjectState(cacheEntry.Entity, EntityState.Deleted);
  
          }
          else
          {
              _dataContext.Books.Attach(newBook);
              _dataContext.ObjectStateManager.ChangeObjectState(newBook, EntityState.Deleted);
          }
          _dataContext.SaveChanges();
      }
  </code></pre>
  
  <p>I'm sure there must be a better way of achieving what I'm trying to do, but I can't for the life of me figure out what!</p>
  
  <p>Any other general comments about the above approach would be appreciated to as I'm about to use it on a large scale project!</p>
  
  <p>Thanks</p>
  
  <p>Ross</p>