1

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

ObjectStateManager 中已存在具有相同键的对象。现有对象处于已修改状态。一个对象只有在被添加的情况下才能再次添加到 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);
            }
4

1 回答 1

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);
}
于 2013-01-29T22:16:32.683 回答