We will soon se that the root cause for this problem is a naming convention. This version of Visual Studio that I have actually seems to enforce a naming convention, and that differs from mine. Maybe you worked in another version, and did not run into the same problem. Let us first fix the problem before we discuss the naming convention.
We can start with the .../Views/Person/Index.cshtml file. Take a look at the parts that lists the items and makes the links that did not work:
Note that the link parameter data is commented out. The links does not contain any information about what item we wish to edit, delete or see in details view.
To understand the @Html.ActionLink stuff just look at the html code that was generated by it. Use 'View source' or whatever it is called in your browser, or hit F12 for all debugging and other tools, while running your project. This is what it looks like to me when I check one row's links:
So, the scaffolding did not like my Id's. A look into some Microsoft database will reveal that foreign keys by standard are composed by table name, underscore and 'Id'. Then it would be likely that the other end of the foreign key, i.e. the key name in the table that has the key, should be named likewise. In our case 'Persons_Id' and 'Phones_Id' respectively.
I tried that. Changed in the database, removed my view folder and the controller, and generated all from scratch again.
Do that, and to generate all from scratch do this:
- Clean and rebuild your solution.
- Open the PhoneBookModel.edmx.diagram file.
- Select the tables (and the view if you already added it) and delete them.
- Right-click the now empty diagram and select 'Update from database'.
- Add the tables as we did in last chapter.
- Rebuild the database project.
- Create the controller and views as we did in the last chapter.
Run your program and naviagate to .../Views/Persons view like we did before.
Looks nice. We even got the first name back for some mysterious reason. To be correct, it should be there, but it is a mystery that it was not when the Id was not following standard. Scaffolding probably ignored Id and thought that FirstName was a key, but could not use it. Try the Edit link:
The Details link also works:
And so does the Delete link:
Everything seems to work fine now, you can list, add, edit and delete persons. There is only one problem, you can delete a person that has a phone, which will leave the phone 'hanging' loose in the database. Normally this is fixed in code some way, or by constraints in the database. The latter would cause our program to crash, so we still would need to fix it in code. However, we really do not care about phones without owners, since we later will add a function to assign a pone to a person.