我有以下代码。因为我正在尝试更新我的数据。但我收到错误消息:
EntityFramework.dll中出现'System.InvalidOperationException'类型的异常,但未在用户代码中处理
附加信息:ObjectStateManager中已存在具有相同密钥的对象。 ObjectStateManager无法使用相同的键跟踪多个对象。
这是我的代码:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="CompanyId,Address,EstbalishYear,Email,IsActive")] CompanyMaster companymaster)
{
if (companymaster.CompanyId == 0)
{
return View(companymaster);
}
CompanyMaster company = db.CompanyMasters.SingleOrDefault(x => x.CompanyId == companymaster.CompanyId);
companymaster.Name = company.Name;
companymaster.InsertedBy = company.InsertedBy;
companymaster.InsertedTime = company.InsertedTime;
companymaster.UpdatedBy = 1;
companymaster.UpdatedTime = DateTime.Now;
ModelState.Remove("Name");
if (ModelState.IsValid)
{
db.Entry(companymaster).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(companymaster);
}
请解释我如何修复此错误消息?
答案 0 :(得分:0)
这是因为您正在使用公司主数据的两个对象实例,实际上这是一个具有相同ID的实体。
One( companyMaster )通过绑定作为Edit方法的参数。
您通过ID通过db.CompanyMasters从数据库中选择的另一个(公司)
你能做的是
请在下面找到示例代码。 另请注意,最佳做法是不在UI层中使用持久性实体模型,而是使用最少的必需字段集定义DTO,然后手动或使用{{3}将其映射到实体}}
[HttpPost] [ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="CompanyId,Address,EstbalishYear,Email,IsActive")] CompanyMaster companymaster)
{
if (companymaster.CompanyId == 0)
{
return View(companymaster);
}
CompanyMaster company = db.CompanyMasters.SingleOrDefault(x => x.CompanyId == companymaster.CompanyId);
company.Address = companymaster.Address;
company.EstbalishYear= companymaster.EstbalishYear;
company.Email = companymaster.Email;
company.IsActive= companymaster.IsActive;
company.UpdatedBy = 1;
company.UpdatedTime = DateTime.Now;
ModelState.Remove("Name");
if (ModelState.IsValid)
{
db.SaveChanges();
return RedirectToAction("Index");
}
return View(companymaster);
}