Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Configure One To Many Relationship in MVC and EntityFrameWork Code First, Code Migration Approach

0.00/5 (No votes)
20 Sep 2015 1  
Configure One To One and One To Many Relationship in MVC and EntityFrameWork Code first, code migration approach

Learn and build web application using MVC and Entity framework code first, code migration approach

Video: https://www.youtube.com/watch?v=GanjklfebEc&index=1&list=PLdmgFSerzv2Kl00tz0qY-jxDPnPowpRaT

Learn MVC and Entity framework code first, code migration approach using sample demo application

Video: https://www.youtube.com/watch?v=OhJtxRvgeK0&list=PLdmgFSerzv2Lhj5dFrD75sz26qGdxpo8Z


Overview

Relationships scenario(One To Many Relationship)

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

  • Course model contains the following properties defined.

  • Open the student model and add the Navigational property for course.
  • Configure the Foreign key by adding CourseId (Primary key of the Course class model) entity in the Student class.
  • 1 to 1 relationship (1 Student can select 1 Course) and
  • 1 to Many relationship ( 1 Course can have Many Students) is established.

  • Generate migration file by executing the command "ADD-Migration" in the package manager console for configuring Foreign Key in Student table in the database side.
  • Script gets generated in migration file.

  • Once the script got generated, update the database.

    Note: Establishing foreign key relationship to the model with student table containing data will generate the foreign key constraint error since Course Id is defined not nullable.

  • 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 established to the Course table.

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

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

  • Modify the Edit Action method and Edit.cshtml viewpage:

  • Add the Dropdownlist to display and provide options to choose the course in the dropdown.

  • 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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here