How to model a Many to many-relationship in code?

Natrium picture Natrium · Jul 9, 2009 · Viewed 25.6k times · Source

Suppose I have 2 tables in a database. eg: Dog & Boss This is a many to many relationship, cause a boss can have more than 1 dog, and a dog can have more than 1 owner. I am the owner of Bobby, but so is my wife.

But many to many is not allowed, so there is a helpertable: DogsPerBoss

How to model this in code?

Class Boss can have a collection of Dogs. Class Dog can have a collection of Bosses. --> at least, that is what I think. Perhaps there are better solutions?

How about extra data that is in the helper-table? Should that be in de Boss-class or in the Dog-class? eg: Nickname (I call the dog "good boy" and my wife calls him "doggie")

I hope my question is kinda clear? Are there any best-practices on what is the best way to achieve this? Can you give me some references?

An ORM (like NHibernate) is not an option.

Answer

John Saunders picture John Saunders · Jul 9, 2009

Why are you talking about tables? Are you creating an object model or a database model?

For an object model, there's no reason a Dog can't have a List<Owner> and an owner have a List<Dog>. Only if you have attributes on the relationship do you need an intermediate class (what UML calls an Association Class). That's when you'd have a DogOwnership class with extra properties, and each Owner would have a List<DogOwnership>, and so would each Dog. The DogOwner would have a Dog, an Owner, and the extra properties.