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

Time:07-02

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

CodePudding user response:

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.

  • Related