N-N relationships

Topics: Writing modules
Jun 16, 2011 at 8:10 PM

I'm following the tutorial here:


For example, if I am a teacher, I can teach 0-many grades.  I see three records:
TeacherGradeRecord (association)

The Teacher would have a Id, Name, and an IList<TeacherGradeRecord> property called Grades
The GradeRecord would have an Id,  Name property
The TeacherGradeRecord would have an Id, TeacherRecord, and GradeRecord

According to the tutorial, at least as far as I could tell, when I save my teacher using _teacherRepository.Create(teacher) I also have to manually save each TeacherGradeRecord to the database, so _teacherGradeRepository.Create(teacher,grade).

I have this all working. The teacher gets created, the TeacherGradeRecord gets inserted into the database. 

Where I'm at now is that when I call _teacherRepository.Get(teacherId), the Grades property on teacher isn't populated.  I thought NHibernate was supposed to pull those automatically...

First things first, can someone tell me if I have the jist of how N-N is supposed to work correct?

Jun 16, 2011 at 9:00 PM

Sounds pretty much right; can you post your Migration code so I can see if you're defining the schema correctly?

Jun 16, 2011 at 9:27 PM

Sure thing...

public int Create()
            // Creating table TeacherRecord
            SchemaBuilder.CreateTable("TeacherRecord", table => table
                .Column("Id", DbType.Int32, column => column.PrimaryKey().Identity())
                .Column("OtherText", DbType.String)
                .Column("StateRecord_Id", DbType.Int32)

                    table => table
                .Column<int>("Id", column => column.PrimaryKey().Identity())
                .Column<string>("Code", column => column.WithLength(2))

                    table => table
                .Column<int>("Id", column => column.PrimaryKey().Identity())
                .Column<string>("Grade", column => column.WithLength(2))

                table => table
                .Column<int>("Id", column => column.PrimaryKey().Identity())

            return 1;
Jun 17, 2011 at 10:17 AM

On the foreign keys, the convention is for id to be lower case - StateRecord_id etc. I'm not 100% sure if that will make the difference, but it's the first thing to try.

Jun 20, 2011 at 2:13 PM

Alright, I'll give it a try and see...I remember trying that before and it didn't work...stay tuned...