Search code examples
c#asp.net-coreentity-framework-coreasp.net-core-webapi.net-6.0

Why do I need to pass students when adding a department in Entity Framework Core?


In Entity Framework Core, while creating OTM relationship we basically pass the reference of one model into another like in below example

Student model:

public class Student 
{
    public int std_id { get; set; } 
    public string std_name { get; set; } 
    public int std_age { get; set; } 
    public int dept_id { get; set; } 
    public Department dept { get; set; } 
}

Department model:

public class Department 
{
    public int dept_id { get; set; } 
    public int dept_name { get; set; } 
    public int dept_capacity { get; set; } 
    public int std_id { get; set; } 

    public ICollection<Student> students { get; set; } 
}

But when we'll add a department, why do we need to pass the students, can't we pass the std_id directly?

Also, when we'll add a Student, we'll have to provide the department details as well, but can't we just pass the dept_id even though the department details will not be saved as well?

So what's the use of reference here? How do I add students and departments?

I'm able to save the department and student but if I add a student then it doesn't save the department details as we have given the reference here, same is happening with Department.

Attaching the screenshot of my Models, Controller, and UI

enter image description here


Solution

  • Usually the Department table is a master table. When you add student to the db, you just provide the department id and save the data in the Students table.

    public class Student 
    {
         public int std_id { get; set; } 
         public string std_name { get; set; } 
         public int std_age { get; set; } 
         [ForeignKey("Department")]
         public int dept_id { get; set; } 
         public Department dept { get; set; } 
    }
        
    public class Department 
    {
        public int dept_id { get; set; } 
        public int dept_name { get; set; } 
        public int dept_capacity { get; set; } 
    }
    

    If you want to save the department details in department table, when you save the student details, you can use cascade insert. Here is the stackoverflow link of the same Cascade Insert in EF