Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

c# - Error "A referential integrity constraint violation occurred"

Can you please help me with my code?

I have 2 models:

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. 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. Error is in dbBooks.Entry(book).State = EntityState.Modified;

If I try to add book.Author = null; it is logically than my AuthorNames` start to disappear...

Also I was trying to put something in Html.HiddenFor, but maybe I was doing something wrong, but nothing changed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, you couldn't modify AuthorName in Book's editor view. 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. So just remove editormodel for author.authorname

Modified books list:

Book bookEdit = dbBooks.Books.ToList().Where(a => a.Id == id).SingleOrDefault();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...