Saturday 24 January 2015

Configure One To Many Relationship in MVC and EntityFrameWork



Relationships scenario( One To Many Relationship)

https://www.youtube.com/watch?v=9qyRIW0FTZ8
  • Course can have multiple Students
  • Student can select only one course




















  • Course Table model
























  • Open the student table and add the Navigational property for course table
  • Configure the Foreign key as CourseId to the Student Table


























  • Execute the command  "ADD-Migration" in the package manager console after the modification in model file for configuring Foreign Key in Student table 
  • Script gets generated 










  • Once the script got generated, update the database.
















































  • Once after executing the "Update-database" command in package manger console, script present in the "up method " of the configuration file will be executed in the SQL Server and Foreign Key will be created 





  • Add the required changes in the create action method in the Student Controller













  • Create a dropdownlist in the viewpage for selecting the course for particular student in the "create.cshtml" view page
















  • Modify the Edit Action method and Edit.cshtml viewpage 


























  • Run the application and test it. 
  • DropdownList for selecting the course will be present and 
  • 1 to Many Relationship and ForeignKey is configured and established

2 comments:


  1. I want to avoid reference (course) When a student already has it. How is it done?
    PerĂº

    ReplyDelete
  2. that’s a nice article, thank you for a great article. It helped me a lot. Keep it up Must Visit Contacteren Acer.

    ReplyDelete