0

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!

Bashir Magomedov
  • 2,841
  • 4
  • 28
  • 44

1 Answers1

2

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

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
  • This is actually that I wanted to avoid :( Thanks for your answer, I got the point. I solved it by creating a helper class that takes Student object and populates non-virtual Comments property for each Course that student attends. This allowed me to keep neat real-world object structure without introducing any stubs. Anyway thanks. I’m marking your answer as accepted because it is correct and actually helped me to understand how EF handles such complex relationships. – Bashir Magomedov Oct 31 '12 at 11:10