无法使用Entity Framework 6更新实体

时间:2014-08-06 09:55:46

标签: c# entity-framework entity

我正在尝试使用以下代码更新实体。

 MemberFee originalMemberFee = db.MemberFees.FirstOrDefault(ann => ann.MemberId == memberFeeViewModel.MemberId && ann.Year == memberFeeViewModel.Year);

  if (originalMemberFee == null)
  {
        db.MemberFees.Add(memberFeeViewModel);
  }
  else
  {
       db.MemberFees.Attach(memberFeeViewModel);
       db.Entry(memberFeeViewModel).State = System.Data.Entity.EntityState.Modified;
  }
  db.SaveChanges();

它成功地创建了实体(在if-sats中)但是当它试图更新实体时它会产生这个错误 Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

1 个答案:

答案 0 :(得分:0)

memberFeeViewModel密钥可能未正确设置。

检查MemberId Year对象的memberFeeViewModel和{{1}}值。如果这些是空的,那么您需要在更新之前提供密钥。