尝试循环Linq查询结果时出错

时间:2013-01-29 22:06:05

标签: linq entity-framework

我需要提取与特定值(CourseCode)对应的任意数量的记录,并将这些记录插入另一个表中。只要Linq代码只返回一条记录,此代码就可以正常工作,但如果有更多,我会得到以下消息:

  

ObjectStateManager中已存在具有相同键的对象。   现有对象处于Modified状态。一个对象只能是   如果它在添加的对象中,则再次添加到ObjectStateManager。

以下是我的代码:

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

1 个答案:

答案 0 :(得分:4)

即使属性值发生更改,循环也会重新添加相同的agentProdTraining对象。为每个循环执行创建一个新实例。

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