简体   繁体   中英

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

What you describe is am: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, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM