实体框架 - 尝试循环访问 Linq 查询结果时出错



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

具有相同键的对象已存在于 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);
            }

即使属性值已更改,循环也会重新添加相同的 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);
}

相关内容

  • 没有找到相关文章

最新更新