When we define a custom business entity as an architecture for a given project, one common issue arises that, how we will consider “Many to Many” relationships? As there is only one entity for each database table, “Many to Many” tables might not be a good choice to make a separate table for that, since this is basically a connector entity.
Case:
Database Simplest Samples – Northwind Employees
Entities: Employees, Territories, EmployeeTerritories, Region
One-to-One: Employees (EmployeeId, ReportsTo)
Description: one employee reports to another employee.
One-to-Many: Region, Territories (TerritoryId, RegionId)
Description: One region has many territories.
Many-to-Many: Employee, Territories, EmployeeTerritories (EmployeeId, TerritoryId)
Description: One employee belongs to many territories and one territory has many employees.
Solutions:
1. Create a single table for the m2m table.
2. Attach the CRUD methods of the m2m table, as static methods, to one of the o2m entity. A common convention can be chosen to attachment, to consider that entity, which is created first. In our case this is author.
3. Attach the m2m primary key, in the “save” instance method (for instance or update) parameter.
4. We can use a collection of objects, in the another tables entity. For example, the employee class may contain a collection of territories or the territory entity may contain a collection of employee object. The save method will be responsible to update the m2m list.
Print | posted on Thursday, July 06, 2006 4:01 AM