INSERT statement conflicted with the FOREIGN KEY

I have this error when I use the create function in my application: The INSERT statement conflicted with the FOREIGN KEY constraint ‘PK_dbo.Books_dbo_Genres_GenreId’

I tried to change the db.savechanges code but it did not work.

Here is a link to my project code: Google drive: https://drive.google.com/open?id=1kTzU3AkAw4z-mMkIOh8WLrNxMhmKkrxO

can someone please take a look? I attached the code. If you run the application and click on admin -> book -> create -> then fill out the information and click submit it gives me the error stated above.

I would guess that Books has a FK constraint against Genres. Meaning that the value entered into the GenreID field (or what ever it’s called on the Books table) MUST exist as a primary key on the Genres table (probably the ID field).

Double check what you’re trying to insert into the Books table. You’re either missing a field, or the value you’re trying to add doesn’t exist on the Genres table…

@DaveMaxwell I attached a link to my code, can you please take a look? My database files are also there.

gid

Look at your book model and your book controller classes. What is required in your book model? Have you accounted for ALL the required elements (hint: you haven’t).

1 Like

You are right. Thanks for helping.
Was missing: genreId=bookVM.Book.GenreId

Do you have any resource, advice on how to get better at .net?

Ran the application and got the same error. Is there something more i have to do?

Debug it and ensure all the fields (especially that GenreID) is actually getting a value.

Thanks it works now.

So my database is stored in a folder called app_data. When i look in my sql server management studion i cannot see that database inside. Do you know can i connect my database to sql server management studio?

Thanks

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.