ObjectStateManager中已存在具有相同键的对象

时间:2013-10-17 08:50:20

标签: c# entity-framework

我在EF中有一个视图,我收到的数据是插入到表格中的。该表仅具有作为主键的ID。它将插入第一条记录,但是一旦我添加第二条记录,我就会收到此错误:

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

我有谷歌的答案,但它似乎没有帮助我想在这里实现。

代码:

var AllTraininOffices = dbIMIS.View_TrainingOffices;

foreach (var office in AllTraininOffices)
{ 
   discounts.EntityNo = office.ID;
   discounts.EntityType = 0;
   discounts.Discount = Discount;
   discounts.DiscountReason = discount.DiscountReason;
   discounts.DiscountAmount = DiscountAmount;
   discounts.CreatedOn = DateTime.Now;
   discounts.CreatedBy = userData.SaicaId;
   discounts.UpdatedBy = userData.SaicaId;
   discounts.UpdatedOn = DateTime.Now;
   discounts.ProductDescription = discount.ProductDescription;
   discounts.ExpiryDate = Convert.ToDateTime(discount.ExpiryDate);
   discounts.FeeCategoryId = GetFeeCategoryID(discount.FeeCategory);
   discounts.DiscountStatus = true;

   db.AddToDiscounts(discounts);

   db.SaveChanges();

}

0 个答案:

没有答案