简体   繁体   中英

Map entities to many-to-many junction table in EF 4.5

At the moment I'm mapping my existing DB tables to new EF 4.5 model via Fluent Api. I've got a questing on how to map following db structure to classes.

Students(pk Id...)
Courses (pk Id...)
Students_Courses (pk Id, fk StudentId, fk CourseId)
Comments (pk Id, fk Students_Courses Id, comment, dateposted...)

The idea is that I may have many reviews per student_course pair. What is the best way to represent my classes in this scenario? The problem here is that I'll probably need to map Comment entity to Students_Courses table and somehow determine to which Student and Course (in terms of classes) this comment belongs. Any suggestions on the design? Thanks!

Maybe you'd like to use Entity Framework Power Tools to reverse-engineer your data model into a "code -first" model with DbContext API.

You will see that something like a StudentCourse class will be generated that looks like this:

public class StudentCourse
{
    public StudentCourse()
    {
        this.Comments = new List<Comment>();
    }

    public int StudentCourseId { get; set; }
    public int StudentId { get; set; }
    public int CourseId { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
    public virtual Course Course { get; set; }
    public virtual Student Student { get; set; }
}

and Comment looking like this:

public class Comment
{
    public int CommentId { get; set; }
    public int StudentCourseId { get; set; }
    public virtual StudentCourse StudentCourse { get; set; }
    ...
}

So comments are related with students and courses through StudentCourse

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