NealR
NealR

Reputation: 10669

Error trying to loop through Linq query results

I need to pull any amount of records that correspond to a specific value (CourseCode), and insert these records into another table. This code works fine as long as the Linq code returns only one record, however if there is any more than that I get the following message:

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.

Below is my 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);
            }

Upvotes: 1

Views: 1130

Answers (1)

roryWoods
roryWoods

Reputation: 4868

The loop is re-adding the same agentProdTraining object even though property values are changed. Create a new instance for each loop execution.

foreach (var pt in prodCodes.ToList())
{
  var agentProdTraining = new AgentProductTraining();

  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);
}

Upvotes: 4

Related Questions