我在数据库里有一个表格叫做“审查”,我用“实体框架”做了“审查”主计长,用阅读/写作动作和观点。所以它代表了所有脚架代码。
这是我的《编辑》专页
@model UniversityApp.Models.Review
@{
ViewBag.Title = "Edit";
}
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Review</legend>
@Html.HiddenFor(model => model.ReviewID)
<div class="editor-label">
@Html.LabelFor(model => model.MovieID, "Movie")
</div>
<div class="editor-field">
@Html.DropDownList("MovieID", String.Empty)
@Html.ValidationMessageFor(model => model.MovieID)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.UserID, "User")
</div>
<div class="editor-field">
@Html.DropDownList("UserID", String.Empty)
@Html.ValidationMessageFor(model => model.UserID)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Rating)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Rating)
@Html.ValidationMessageFor(model => model.Rating)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
您可以看到脚手架机制增加了外国值密钥的编辑器。 我不想让用户在已经进行过审查后能够更改手动用户代号或电影代号, 因此我删除了这个代码。 但是在编辑复议条目时, 我在数据库 SaveCchanges () 中发现错误 :
外国密钥值无法插入, 因为相应的主密钥值不存在 。 [外国密钥限制名称 = Review_ User]
为了保护旧用户身份和电影身份价值,
此处为“审查主计长”中的编辑动作代码 :
public ActionResult Edit(int id)
{
Review review = db.Reviews.Find(id);
ViewBag.MovieID = new SelectList(db.Movies, "MovieID", "Title", review.MovieID);
ViewBag.UserID = new SelectList(db.Users, "UserID", "UserName", review.UserID);
return View(review);
}
[HttpPost]
public ActionResult Edit(Review review)
{
if (ModelState.IsValid)
{
db.Entry(review).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.MovieID = new SelectList(db.Movies, "MovieID", "Title", review.MovieID);
ViewBag.UserID = new SelectList(db.Users, "UserID", "UserName", review.UserID);
return View(review);
}
<强 > EDIT: 强 >
I have tried the methods described, but I am still having problems. Now the error message I get is this: A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship. I don t know what am I doing wrong. The error is trigered on this line of code:
db.Entry(review).State = EntityState.Modified;