我有一张名为SectionUser的桌子像这样:
USER_ID (varchar(255)) (主键)NAME (varchar(255))以下是示例值:
USER ID | NAME
--------+--------------
EVTAB | ELMER TABER
FAYKVIL | FAYK VILLET每当我单击网页表中的“编辑”选项卡时,就可以检索数据。当我试图编辑“名字”的时候。我可以成功地编辑这个名字。但是我无法编辑USER_ID (这是我的主键)
当我尝试调试模式时,当我在textbox中在USER_ID下编辑数据时,它将不会获得USER_ID数据。但是它从NAME中的文本框中获取数据。
主计长:
public ActionResult EditUser(string USER_ID)
{
if (USER_ID == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SectionUser section = db.SectionUsers.Find(USER_ID);
if (section == null)
{
return HttpNotFound();
}
return View(section);
}
[HttpPost]
public ActionResult EditUser(Users User)
{
try
{
if (ModelState.IsValid)
{
_context.Entry(User).State = EntityState.Modified;
_context.SaveChanges();
return RedirectToAction("Users");
}
}
catch(Exception e)
{
e.ToString();
}
return View(User);
}视图(cshtml)
@using (Html.BeginForm("EditUser", "Admin", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Section</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.USER_ID)
<div class="form-group">
@Html.LabelFor(model => model.USER_ID, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.USER_ID, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.USER_ID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.NAME, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.NAME, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.NAME, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}我之所以编辑我的主键,是因为给我的是数据库模型。SectionUser有一个UserRole的外键。所以我用了级联更新。每当我编辑USER_ID of SectionUser时,UserRole USER_ID也会被更新。
发布于 2018-07-20 10:23:12
这就是我试过的:
我创建了一个更新主键的存储过程。
UPDATE dbo.SectionUser
SET USER_ID = @USER_ID
WHERE NAME = @NAME然后,我创建了一个函数void execEditUserId(),我通过EditUser()操作方法调用该函数。
发布于 2018-07-20 01:45:53
IMHO您应该重构您的db模型,以便有一个独立的主键列,而不是其他列。实体框架或其他ORM基于主键更新数据,如果在代码中更新主键值本身,则实体框架无法确定要更新的行。
另一种方法可以是使用经典的ado.net并编写自己的sql查询。
@Camilo回答的代码会给出一个运行时错误:
{“属性'user_id‘是对象的密钥信息的一部分,不能修改。"}
https://stackoverflow.com/questions/51433555
复制相似问题