Musings<Biefeld>
- curiosities of development, life, the universe and everything -
Posts Tagged ‘Mapping’
Wednesday, September 3rd, 2008

Ran into an issue today when I needed to get a column from a many to many relational table.  It was not in any table that mapped directly to any of my entities, so I was somewhat dumb founded on how to proceed.

 

An example would be if you have a school domain where there are multiple Students associated with multiple Courses.  You would most likely have a Student and Course entity that map to their respective database tables and a Student_Course table that does not map directly to anything.  Depending on the point of view you are working with you would probably have the Student with a collection of Course or vice versa.  For this example let’s say that we are looking at it from the perspective of a student.  As a Student I would want to see my final grade for the Course , for simplicity let’s say that the final grade is stored in the Student_Course table.  The most likely place to want that Grade is on the Course.  When you are mapping the Course you would have a property for Grade mapped out,

<class name="Course" table="Course">

    <id name="Id" column="Id" />
    <property name="Name" column="Name" />
    <property name="Description" column="Description" />
    <property name="FinalGrade" column="FinalGrade" />

</class>

but where would you specify the relational table to pull the Grade from? With the code above NHibernate will blow chunks, saying it cannot find the column FinalGrade in the Course table even though it is a property on your Course entity.

 

Well, in NHibernate there is a <join> mapping that you can use to map columns from other tables to the entity you are working with.  So, in the example we would replace the mapping:

<property name="FinalGrade"column="FinalGrade"/>

with:

<join table="Student_Course"optional="true">
    <key column="CourseId"/>
    <property name="FinalGrade"column="FinalGrade"/>
</join>

We would specify the many to many relational table with the table parameter.  Set the key column to the CourseId so NHibernate can join on the Id and you specify the property/column as normal.  Note the optional attribute, this is used to specify if you still want results returned where FinalGrade may be null.  This is more apparently useful in situations where you are loading courses and you don’t really care if there are FinalGrades associated with the Courses. 

 

Now when I am looking at a Student’s Courses the will all have the final grade populated.

Musings<Biefeld> is proudly powered by WordPress
Entries (RSS) and Comments (RSS).