[英]Error “A referential integrity constraint violation occurred”
Can you please help me with my code? 您能帮我提供我的代码吗?
I have 2 models: 我有2个型号:
public class Author
{
public int Id { get; set; }
public string AuthorName { get; set; }
public IEnumerable<Book> Books { get; set; }
}
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public int YearPublish { get; set; }
public int Price { get; set; }
public int? AuthorId { get; set; } //FK
public Author Author { get; set; } //navigation property
}
And trying to make an Edit function. 并尝试制作一个Edit函数。 Controller code:
控制器代码:
// GET: Books/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return HttpNotFound();
}
Book bookEdit = dbBooks.Books.Include(a => a.Author).Where(a => a.AuthorId == id).Single();
return View(bookEdit);
}
// POST: Books/Edit/5
[HttpPost]
public ActionResult Edit(Book book)
{
if (ModelState.IsValid)
{
// TODO: Add update logic here
//book.Author = null; //AuthorName cant be edited
dbBooks.Entry(book).State = EntityState.Modified;
dbBooks.SaveChanges();
return RedirectToAction("Index");
}
return View(book);
}
And my View: 我的看法:
<div class="form-horizontal">
<h4>Book</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.Author.AuthorName, "AuthorName", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Author.AuthorName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Author.AuthorName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.YearPublish, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.YearPublish, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.YearPublish, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Price, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Price, "", 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>
And when i try just to click Save button (even if i dont do any changes) an error occured: A referential integrity constraint violation occurred: The property value(s) of 'Author.Id' on one end of a relationship do not match the property value(s) of 'Book.AuthorId' on the other end. 当我尝试仅单击“保存”按钮(即使我不进行任何更改)时,发生了错误:发生参照完整性约束违反:关系一端的“ Author.Id”的属性值不匹配另一端的'Book.AuthorId'的属性值。 Error is in dbBooks.Entry(book).State = EntityState.Modified;
错误出在dbBooks.Entry(book).State = EntityState.Modified;
If I try to add book.Author = null;
如果我尝试添加
book.Author = null;
it is logically than my AuthorNames` start to disappear... 从逻辑上讲,我的AuthorNames开始消失了...
Also I was trying to put something in Html.HiddenFor, but maybe I was doing something wrong, but nothing changed. 我也试图在Html.HiddenFor中放一些东西,但是也许我做错了什么,但是什么都没有改变。
Well, you couldn't modify AuthorName in Book's editor view. 好吧,您无法在Book的编辑器视图中修改AuthorName。 You need another view for Author to modify it.
您需要作者另一个视图来修改它。
book.Author
- cannot be null
, becouse its navigation property and can only be like readonly mode. book.Author
不能为null
,因为它具有导航属性,只能像只读模式一样。 So just remove editormodel for author.authorname 因此,只需删除author.authorname的editormodel
Modified books list: 修改后的书籍清单:
Book bookEdit = dbBooks.Books.ToList().Where(a => a.Id == id).SingleOrDefault();
Look what you need to do, i got it now. 看看你需要做什么,我现在明白了。 You just need selectList of all Author's and in a view name will be auto selected on AuthorId book's field.
您只需要选择所有作者的selectList,即可在AuthorId图书的字段中自动选择视图名称。 Make new one form-group with
与建立新的一个表单组
<div class="form-group">
@Html.LabelFor(model => model.AuthorId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@(Html.DropDownListFor(p => p.AuthorId, (SelectList)ViewBag.Authors, new { @class = "form-control" }))
@Html.ValidationMessageFor(model => model.AuthorId, "", new { @class = "text-danger" })
</div>
</div>
And in Your Edit action: 在您的“编辑”操作中:
// GET: Books/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return HttpNotFound();
}
Book bookEdit = dbBooks.Books.Where(a => a.Id == id).Single();
// UPDATED
var list = dbBooks.Books.Select(x => new { ID = x.Id, AuthorName = x.AuthorName });
ViewBag.Authors = new SelectList(list, "Id", "AuthorName");
// UPDATED
return View(bookEdit);
}
Again many thanks! 再次非常感谢!
But using DropDownList dont allow me to edit Author`s name.. But that solution is rly good. 但是使用DropDownList不允许我编辑作者的名字。但是这种解决方法非常好。
I need to edit all 4 fields like name, title, year and price. 我需要编辑所有4个字段,例如名称,标题,年份和价格。
I try to make something like composite model: 我尝试制作类似复合模型的内容:
public class BookAuthorCompositeModel
{
public Author author { get; set; }
public Book book { get; set; }
}
Change my get method: 更改我的get方法:
// GET: Books/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return HttpNotFound();
}
var compModel = new BookAuthorCompositeModel();
compModel.book = dbBooks.Books.ToList().Where(a => a.Id == id).SingleOrDefault();
compModel.author = dbBooks.Authors.ToList().Where(x => x.Id == id).SingleOrDefault();
return View(bookEdit);
}
and it displays all I need (i tap "edit" and see information about name, title, year and price). 并显示所有我需要的内容(我点击“编辑”,然后查看有关名称,职务,年份和价格的信息)。
My view is: 我的看法是:
@model BookStorage.Models.BookAuthorCompositeModel
@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Book</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.book.Id)
<div class="form-group">
@Html.LabelFor(model => model.author.AuthorName, "AuthorName", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.author.AuthorName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.author.AuthorName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.book.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.book.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.book.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.book.YearPublish, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.book.YearPublish, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.book.YearPublish, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.book.Price, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.book.Price, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.book.Price, "", 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>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
but something wrong is in Post method: 但是Post方法有问题:
[HttpPost]
public ActionResult Edit(Book book)
{
if (ModelState.IsValid)
{
dbBooks.Entry(BAmodel.book).State = EntityState.Modified;
dbBooks.Entry(BAmodel.author).State = EntityState.Modified;
dbBooks.SaveChanges();
return RedirectToAction("Index");
}
return View(book);
}
dbBooks.SaveChanges(); dbBooks.SaveChanges(); leads to error.. I think using this kind of ViewModel helps to edit all rows, but it doesnt sade data to DB...
导致错误..我认为使用这种ViewModel有助于编辑所有行,但不会将数据发送到DB ...
Maybe you could help with this please? 也许您可以帮忙吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.