Many-to-Many Association

Many-to-many associations use an intermediate table that has a foreign key to the tables of both associated entities. An object uses several objects of another type, and this latter object references several objects of the first type. As is always the case for many-to-many mappings in relational databases, we need the third table which provides cross-references for the many-to-many relationship.

The database contains the Employees and Territories tables, and the EmployeeTerritories table, which provides cross-references for the many-to-many relationship.

images_AssociationManytoMany-table

We perform the following sequence of operations:

create an NHibernate model;
add the Employees, Territories, and EmployeeTerritories tables to the model.

As a result, we have the following model:

images_AssociationManytoMany-model

The association between the Employee and Territory entities looks as follows:

images_AssociationEditorManytoMany

The Territories navigation property of the Employee type is a many-to-many property to a Set collection of objects with the Territory type. The values for the objects in this collection can be found by looking for entries in the table for Territory objects with TerritoryID equal to the values in the TerritoryID column of the EmployeeTerritories table with the value of EmployeeID equal to this object's EmployeeID.

The Employees navigation property of the Territory type is a many-to-many property to a Set collection of objects with the Employee type. The values for the objects in this collection can be found by looking for entries in the table for Employees objects with EmployeeID equal to the values in the EmployeeID column of the EmployeeTerritories table with the value of TerritoryID equal to this object's TerritoryID.

In our example, both navigation properties are mapped as a Set, although for many-to-many associations, we can use any other type of collection mapping, if needed.

note Note

For a special case of many-to-many association, when an association is created between a class and a complex type, refer to Support of Many-to-Many Mapping for Component Navigation Properties

 

ExpandedToggleIcon        See Also


Send feedback on this topic

© 2008 - 2024 Devart. All rights reserved.