locked
Code first entity framework - One to many relationship RRS feed

  • Question

  • User1164332849 posted

    In my project, I have an Admin who adds instructors, then each instructor adds his students.

    Until now, I only created Instructor class :

     public class Instructor
        {
            public int InstructorID { get; set; }
    
            [DisplayName("Name")]
            [Required]
            public string InstructorName { get; set; }
    
            [EmailAddress]
            [DisplayName("Email")]
            public string Email { get; set; }
    
            [DisplayName("Password")]
            [DataType(DataType.Password)]
            public string Instructorpassword { get; set; }
        }

    Student class:

    public class Student
        {
            [Required]
            [DisplayName("Student ID")]
            public int StudentRegNum { get; set; }
    
            [Key]
            public int studentID { get; set; }
    
            [DisplayName("Student Name")]
            [Required(ErrorMessage = "Please enter student name")]
            public string studentName { get; set; }
    
            [DisplayName("Student Email")]
            [Required(ErrorMessage = "Please enter student email")]
            [EmailAddress]
            public string studentEmail { get; set; }
    
    
            public decimal grade { set; get; }
    
            [DataType(DataType.Password)]
            public string Studentpassword { get; set; }
        }

    And finally, my db context:

    public class CompilerCourseContext : DbContext
        {
    
            public DbSet<Instructor> Instructors { get; set; }
    
            public DbSet<Student> Students { get; set; }
    
    
    
        }

    Should I add the following to Student class? 

    public virtual Instructor instructor {get; set;}
    public int InstructorID {get; set;}

    And 

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

    to the instructor class? 

    Won't students be associated to the instructor who added them by default? 

    Saturday, February 11, 2017 1:24 PM

All replies

  • User-821857111 posted

    HWasp

    Should I add the following to Student class? 

    public virtual Instructor instructor {get; set;}
    public int InstructorID {get; set;}

    And 

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

    to the instructor class? 

    Yes.

    HWasp

    Won't students be associated to the instructor who added them by default? 

    No. You need to add the navigation properties described above to establish the relationship.

    Tuesday, February 14, 2017 8:32 AM