Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to define common property for two different entities in EF core?

I have two entities Student and course as below

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    [System.Text.Json.Serialization.JsonIgnore]
    public virtual IList<Course> Courses { get; set; }
}

public class Course
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual IList<Student> Students { get; set; }

    [ForeignKey(nameof(TeacherId))]
    public  int TeacherId {get;set;}
    public Teacher Teacher { get; set; }
}

Now I want to add list of grades to two entities containing grade and id of the course or Student depending on the situation. Do I have to define a entity grade with studentId and CourseId or is there any other way to do it without creating entity

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What you describe is a m:n-relationship between Course and Student with the extra information of the grade that was awarded for the participation. By creating the two navigation properties Student.Courses and Course.Students you have already created an implicit crosstab between the entities. In order to add the grade, I’d propose to create a dedicated entity, e.g. CourseParticipation that defines the relationship between Course and Student and also carries the extra information (up to now, the grade, later maybe more):

public class CourseParticipation
{
    public int Id { get; set; }
    public int CourseId { get; set; }
    public Course Course { get; set; }
    public int StudentId { get; set; }
    public Student Student { get; set; }
    public int Grade { get; set; }
}
public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    [System.Text.Json.Serialization.JsonIgnore]
    public virtual IList<CourseParticipation> Courses { get; set; }
}
public class Course
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual IList<CourseParticipation> Participants { get; set; }

    [ForeignKey(nameof(TeacherId))]
    public  int TeacherId {get;set;}
    public Teacher Teacher { get; set; }
}

This way, you make the relationship explicit and are prepared for later additions to the relationship.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading