2

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

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

}
4

0 回答 0