Association classes

Associations define the relation between Classes. Whenever you need some additional information on that relationship an association class will come in handy.

Model1:

Model 1 Association classes.png

Even if the Association class is mostly used for many to many relationships, you can just as well use them on the association of any cardinality.

Model2:

Model 2 Association classes.png

OR-mapping (the process of taking an object oriented model (a standard UML class diagram) and transform it to a relational database schema (tables, fields, primary and foreign keys) ) will turn this model into three tables; one to store Person, one to store Flight and one to store Booking.

If you had not used the association class, OR-mapping would still create three tables due to the many to many association. The third table would store two foreign keys, one to identify the Person and one to identify the Flight. The third table would implicitly be named, if you did not explicitly give it a name, to PersonFlight or FlightPerson. This table the DB-guys often refer to as a link table.

The funny thing is that modeling this another way will give the exact same OR-Mapping result:

Model 3:

Model 3 Association classes.png

This will also end up in the database as three tables where Booking points out Person and Flight with one foreign key for each. So for a DB-centric-guy, this is the same… To an OO-Guy this is NOT the same.

What is the difference

The rules that association classes adhere to in any well-behaving MDD framework are these:

1. Lifetime control; The booking cannot be explicitly created. It is created as a consequence of associating a Person with a Flight: aPerson.Flights.Add(aFlight). And it is destroyed automatically whenever the association is removed: aPerson.Flights.Remove(aFlight)

2. Uniqueness; In UML one instance must be unique in the relation, you cannot add one person to a flight twice. This way the use of the association class has effectively given the UML reader the information that a person can only be one passenger at a time and not two.

So whenever you see the need for lifetime control and uniqueness you should use the association class. It will help the reader and it will help the developer – the DB-guy will not know the difference but then again they seldom do.

(Side note: Entity Framework does not currently support association classes. They argue that there is no need since the Model2 can be replaced with Model3 (No surprise since they are db guys ) )

Adding a link object

Look at Adding a link object for an example of EAL to help you easily handle the adding of an link object

This page was edited 16 days ago on 04/02/2024. What links here