10

I'm looking to create a many to many relationship using NHibernate. I'm not sure how to map these in the XML files. I have not created the classes yet, but they will just be basic POCOs.

Tables

Person
personId
name

Competency
competencyId
title

Person_x_Competency
personId
competencyId

Would I essentially create a List in each POCO for the other class? Then map those somehow using the NHibernate configuration files?

Chris Stewart
  • 3,303
  • 9
  • 36
  • 55

1 Answers1

23

You can put the many-to-many relation to either class, or even to both. This is up to your domain model. If you map it to both, one of them is inverse.

class Person
{
  // id ...
  IList<Competency> Competencies { get; private set; }

  // you domain model is responsible to manage bidirectional dependencies.
  // of course this is not a complete implementation
  public void AddCompetency(Competency competency)
  {
    Competencies.Add(competency);
    competency.AddPerson(this);
  }
}

class Competency
{
  // id ...
  IList<Person> Persons { get; private set; }
}

Mapping:

<class name="Person">
  <id ....>
  <bag name="Competencies" table="Person_x_Competency">
    <key column="personId"/>
    <many-to-many class="Competency" column="competencyId"/>
  </bag>
</class>

<class name="Competency">
  <id ....>
  <bag name="Persons" table="Person_x_Competency" inverse="true">
    <key column="competencyId"/>
    <many-to-many class="Person" column="personId"/>
  </bag>
</class>

Only make it bidirectional if you really need it.

By the way: it is much better to write the classes first and create the database design afterwards. The database can be exported from the mapping files. This is very useful.

Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
  • 1
    I guess I don't really understand why I would, or wouldn't, need bidirectional and what impact it haves if used when not really needed. – Chris Stewart Apr 27 '10 at 17:23
  • 1
    It depends on which property paths you need to "navigate" in your model. Do you regularly want to see the competencies of a person? Most probably you will, so it will be a good idea to have the competencies available in the person. Do you frequently need to know all the persons which have a certain competency? I guess this is an exception and could also be found by a query. – Stefan Steinegger Apr 28 '10 at 07:13
  • Shouldn't the name of the bag in the second class mapping be "Persons" and not "Competencies"? – Mateo Feb 23 '11 at 04:19