Thursday, 21 March 2013

MVC 4 - Simple CRUD (Entity Framework) example with composite primary key PART 1

Watch this example on YouTube:


In my database I have table called TestCompositePrimary - it has composite primary key.



Table is related to StyleMaster and ColorMaster








This step by step tutorial will show you how to add/edit/delete records in this table using MVC 4 /Entity Framework EF.
First - create new project


Ensure it is Internet application


Right click Models folder and add new item

Follow the instructions (connect to database and select tables - all details in the YouTube example)
Once completed you will be able to see all 3 tables (that we need for this example)

Rebuild the solution (you have to rebuild solution whenever you modify EF)

Now right click Controller folder and add new controller.

 Name new controller TestController


Ensure that template, model class and data context class are correct and pointing to our test table.



 Test controller is created with all CRUD functionality (add,delete, etc).  Also in View folder another subfolder has been created with all screens that are needed to add/edit/delete items in our table.
Lets run the program and point to http://localhost:50566/Test (your port number may be different than my 50566).

 you can view all records in out table.  Click create new and add new record - program will create new record.  Now try to edit or delete record - you will get error "The number of primary key values passed must match number of primary key values defined on the entity."


 Our table has composite primary key, we have to let our program know about it.
First open Index.cshtml file that is located in test folder in View








 Go to part 2
http://howtodomssqlcsharpexcelaccess.blogspot.ca/2013/03/mvc-4-simple-crud-entity-framework_21.html

1 comment:

  1. Thank you, this was very helpful with a current MVC4 project!

    ReplyDelete