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






4.67/5 (4 votes)
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 theStudent
class. - 1 to 1 relationship (1
Student
can select 1Course
) and - 1 to Many relationship ( 1
Course
can have ManyStudents
) 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 sinceCourse 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 theCourse
table. - Add the required changes in the create action method in the Student Controller.
- Create a
dropdownlist
in theviewpage
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.