MichalObi
MichalObi

Reputation: 133

SaveChanges() conflicted with the FOREIGN KEY

I tried to do this official tutorial:

http://docs.asp.net/en/latest/tutorials/your-first-aspnet-application.html.

While running the application I can create Authors. However, an exception is thrown in BooksController.cs (generated from Scaffolded Item ) if I try to create Books.

//enter code here
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(Book book)
    {
        if (ModelState.IsValid)
        {
            _context.Book.Add(book);
            _context.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewData["AuthorID"] = new SelectList(_context.Set<Author>(), "AuthorID", "Author", book.AuthorID);
        return View(book);
    }
//enter code here

I get the following exception message when the debugger hits the line _context.SaveChanges() in the aforementioned code:

The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_Book_Author_AuthorID\". The conflict occurred in database \"aspnet5-ContosoBooks-6c8514e9-1385-411c-bc72-2620ec2f43ec\", table \"dbo.Author\", column 'AuthorID'."}

It seems to be problem with my newly created book. This item simply doesn't have an AuthorID foreign key to the Authors table.

Is it just for me, or did I do something wrong ? How can I fix this foreign key exception in the example that I just mentioned?

Now my Author.cs look like this

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

    namespace ContosoBooks.Models
    {
        public class Author
        {
            public int AuthorID { get; set; }
            [Required]
            [Display(Name = "Last Name")]
            public string LastName { get; set; }

            [Display(Name = "First Name")]
            public string FirstMidName { get; set; }

            public virtual ICollection<Book> Books { get; set; }
        }
    }

And my view for create book

@model ContosoBooks.Models.Book

@{
    ViewData["Title"] = "Create";
}

<h2>Create</h2>

<form asp-action="Create">
    <div class="form-horizontal">
        <h4>Book</h4>
        <hr />
        <div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="AuthorID" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select asp-for="AuthorID" class ="form-control"></select>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="Genre" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="Genre" class="form-control" />
                <span asp-validation-for="Genre" class="text-danger" />
            </div>
        </div>
        <div class="form-group">
            <label asp-for="Price" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="Price" class="form-control" />
                <span asp-validation-for="Price" class="text-danger" />
            </div>
        </div>
        <div class="form-group">
            <label asp-for="Title" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="Title" class="form-control" />
                <span asp-validation-for="Title" class="text-danger" />
            </div>
        </div>
        <div class="form-group">
            <label asp-for="Year" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="Year" class="form-control" />
                <span asp-validation-for="Year" class="text-danger" />
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
</form>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
}

Upvotes: 0

Views: 1282

Answers (2)

Majed
Majed

Reputation: 53

Your Book model is having relation with model Author, as I am looking into you referenced link the Book model has AuthorId.

You need provide AuthorId to Book model while saving or you need to first save Author and then get that saved AuthorId and set in Book model. (As per you models a book must have an author).

Upvotes: 0

JamieD77
JamieD77

Reputation: 13949

Your problem is that you're not giving parameter Book book an AuthorID. based on the example you're looking at, the Book model has [ScaffoldColumn(false)] above public int AuthorID in the Book model. This means this field will not have an input created when you use the generated from Scaffolded Item approach. Remove [ScaffoldColumn(false)] and regenerate your controller/views for Books.. or just add the field to your Book views manually.

You may want to try this tutorial out if you're trying to learn MVC http://pluralsight.com/training/Player?author=scott-allen&name=mvc4-building-m6-ajax&mode=live&clip=0&course=mvc4-building

Upvotes: 1

Related Questions