title: Check if EF entity already exist in current context
body: <p>I am aware of the fact that there a several questions about this already, but none of them really solves my problem:</p>
  
  <p><strong>APPLICATION BACKGROUND</strong></p>
  
  <p>I have a web application that uses Entity Framework 6.1 Code first. I'm using Repository pattern within my DAL, which means, I have Repo's that queries my context and returns the results to Services, which then uses automapper to map my entity to a view model, and then returns a VM. Services are called by Web API methods.</p>
  
  <p>Based of the above architecture, its clear that I'm using <strong>detached entities.</strong></p>
  
  <p>The issue i'm having is with updating (PUT) existing entities. The flow looks like this:</p>
  
  <p>Angular Issue HTTP PUT to WebAPI method passing VM as parameter. 
  WebAPI then calls a Service method, passing the VM as parameter.
  Services method converts VM to EF entity using automapper
  Service method then calls respective repository, passing new instance of detached EF entity as parameter.</p>
  
  <p><strong>Example of Service method:</strong></p>
  
  <pre><code>    public async Task&lt;List&lt;DependantViewModel&gt;&gt; SaveDependants(int customerId, List&lt;DependantViewModel&gt; dependantViewModels)
      {
          var dependantEntities = Mapper.Map&lt;List&lt;DependantViewModel&gt;, List&lt;Dependant&gt;&gt;(dependantViewModels);
  
          bool result = false;
          foreach (var dependantEntity in dependantEntities)
          {
              result = await _dependantRepository.InsertOrUpdate(dependantEntity);
              if (result != true)
              {
                  // log errror
              }
          }
  
          return Mapper.Map&lt;List&lt;Dependant&gt;, List&lt;DependantViewModel&gt;&gt;(dependantEntities);
      }
  </code></pre>
  
  <p><strong>BaseRepo:</strong></p>
  
  <pre><code>    public virtual async Task&lt;bool&gt; InsertOrUpdate(TE entity)
      {
          if (entity.Id == 0 || entity.Id == ModelState.New)
          {
              // insert new item
              _context.Entry&lt;TE&gt;(entity).State = EntityState.Added;
          }
          else
          {
              // update existing item
              _context.Entry&lt;TE&gt;(entity).State = EntityState.Modified;
              _context.Entry&lt;TE&gt;(entity).Property(o =&gt; o.CreatedUserId).IsModified = false;
              _context.Entry&lt;TE&gt;(entity).Property(o =&gt; o.CreatedDate).IsModified = false;
          }
          return await _context.SaveChangesAsync() &gt; 0;
      }
  </code></pre>
  
  <p>Exception happens when trying to set:</p>
  
  <p><strong>_context.Entry(entity).State = EntityState.Modified;</strong></p>
  
  <blockquote>
    <p>Attaching an entity of type
    'Business.Data.Entities.Customer.Dependant' failed because another
    entity of the same type already has the same primary key value. This
    can happen when using the 'Attach' method or setting the state of an
    entity to 'Unchanged' or 'Modified' if any entities in the graph have
    conflicting key values. This may be because some entities are new and
    have not yet received database-generated key values. In this case use
    the 'Add' method or the 'Added' entity state to track the graph and
    then set the state of non-new entities to 'Unchanged' or 'Modified' as
    appropriate.</p>
  </blockquote>
  
  <p>As far as I understand, this happens because the detached entity needs to be attached first before setting the entity state. The issue with this is, I can't attach the entity, because its already in the context.Dependant.local collection. For some reason, entity framework is already tracking the entity.</p>
  
  <p>Is there a way to first check if an entity exists in the context, and if it doesn't, then attach, otherwise, retrieve the already attached entity, and apply the changes from the modified entity to the attached entity, if that makes sense.</p>
  
  <p>Appreciate any feedback</p>