title: Error trying to loop through Linq query results
body: <p>I need to pull any amount of records that correspond to a specific value (<code>CourseCode</code>), and insert these records into another table. This code works fine as long as the <code>Linq</code> code returns only one record, however if there is any more than that I get the following message: </p>
  
  <blockquote>
    <p>An object with the same key already exists in the ObjectStateManager. 
    The existing object is in the Modified state.  An object can only be
    added to the ObjectStateManager again if it is in the added.</p>
  </blockquote>
  
  <p>Below is my code: </p>
  
  <pre><code>            if (_db == null) _db = new AgentResourcesEntities();
  
              var prodCodes = from records in _db.CourseToProduct
                                where records.CourseCode == course.CourseCode
                                select records;
  
              foreach (var pt in prodCodes.ToList())
              {
                  agentProdTraining.SymNumber = symNumber;
                  agentProdTraining.CourseCode = course.CourseCode;
                  agentProdTraining.ProductCode = pt.ProductCode;
                  agentProdTraining.DateTaken = course.DateTaken;
                  agentProdTraining.Method = course.Method;
                  agentProdTraining.LastChangeOperator = requestor;
                  agentProdTraining.LastChangeDate = DateTime.Now;
                  agentProdTraining.DateExpired = course.ExpirationDate;
                  agentProdTraining.ProductCode = pt.ProductCode;
                  agentProdTraining.NoteId = pt.NoteId;
  
                  _db.AgentProductTraining.AddObject(agentProdTraining);
                  _db.SaveChanges();
  
                  PtAdded++;
  
                  EventLog.WriteEntry(sSource, "Product Training added", EventLogEntryType.Warning);
              }
  </code></pre>