嗨我试图更新操作但是在更新它时显示错误接近db。保存更改()。
它显示了下面提到的错误
EntityFramework.dll中发生了'System.Data.Entity.Infrastructure.DbUpdateException'类型的异常,但未在用户代码中处理
所以我搜索了内部异常。它显示了下面提到的错误。
“违反PRIMARY KEY约束'PK__UserRights__0155B971'。无法在对象'dbo.UserRights'中插入重复键。\ r \ n语句已终止。”}
我的控制器代码
public ActionResult UsetBasedAuthenticationEditSave(UserAuthenticationViewModel objuavm )
{
ViewBag.UserID = new SelectList(db.UserDetails, "UserID", "UserName", objuavm.UserID);
ViewBag.ModuleID = new SelectList(db.UserModules, "ModuleID", "ModuleName", objuavm.ModuleID);
ViewBag.SubModule = new SelectList(db.UserModules, "SubModule", "SubModule", objuavm.SubModule);
var objuserrightsresult = db.UserRights.Find(objuavm.UserRitsID);
if(objuserrightsresult!=null)
{
objuserrightsresult.UserID = objuavm.UserID;
objuserrightsresult. ModuleID = objuavm.ModuleID;
objuserrightsresult. Toview = Convert.ToBoolean(objuavm.Toview);
objuserrightsresult. ToAdd = Convert.ToBoolean(objuavm.ToAdd);
objuserrightsresult. ToEdit = Convert.ToBoolean(objuavm.ToEdit);
objuserrightsresult. ToDelete = Convert.ToBoolean(objuavm.ToDelete);
objuserrightsresult.IsActive = Convert.ToBoolean(objuavm.IsActive);
objuserrightsresult.IsDeleted = Convert.ToBoolean(objuavm.IsDeleted);
objuserrightsresult. EditedDate = DateTime.Now;
objuserrightsresult. LastActiveOn = DateTime.Now;
objuserrightsresult. RowID = Guid.NewGuid();
objuserrightsresult. CreatedSeesionID = Guid.NewGuid();
objuserrightsresult. EditedSessionID = Guid.NewGuid();
objuserrightsresult. OfflineMode = false;
objuserrightsresult.OfflineID = Guid.NewGuid();
objuserrightsresult.SubModule = objuavm.SubModule;
db.UserRights.Add(objuserrightsresult);
}
db.SaveChanges();
return RedirectToAction("UserBasedAuthenticationIndex");
}
答案 0 :(得分:2)
评论此行:
//db.UserRights.Add(objuserrightsresult);
由于您正在进行更新,因此不应再次添加...只需更新字段值,然后只需调用db.SaveChanges();