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

2020-02-02 18:13发布

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.

12条回答
家丑人穷心不美
2楼-- · 2020-02-02 19:06

Every time we need to think about real life and our needs. In this case, the key point is which one should have another one.

In real life a dog and a boss may dont have each other. But your software needs should effect this relationship.

  • For example if you are developing a veterinarian patient management software, for a veterinarian who cures stray dogs then Patient(dog)-Guardian(boss) relationship should be like this : Bosses must have at least one dog and dog may dont have any boss(then boss id is the foreign key of this relationship) that means in your design the dog class must hold a collection of bosses. Why because any boss instance can not be created without any dog(s). We can get this decision with the the data logic too. Lets think about when you are trying to save your dog and boss classes in database. If the relation condition like above, while saving a boss you should insert a junction record into the junction table.

  • If you are developing that software a veterinarian who dont cures stray dogs, then Patient - Parent relationship needs to be like this: A dog must have at least one boss and boss must have at least a dog, and we need to consider this special relationship case. That means any of these classes instances can not be created without eachother. So we need to define this speciality in our OO design. That means we need a class which represents this dependency. Ofcourse this dependency will stored in junction table.

-If your software developed for a veterinarian who cures stray dogs and these dogs adopted by bosses your design should be like this: Any dog may dont have boss(es) and any boss may dont have any dog(s) until adoption. In this case our OO design needs to care about this special case. This case a little bit same as the first one. So we can add collection of any class into other one. But, any software needs like this will effect other needs. Like reporting. If veterinarian concerns about dogs which adopted by boss(es), sooner or later he asks a report which dog adopted by who. Like in the sentence, (dogs adopted by boss(es)) it is better if dog class contains a collection of boss classes.

I hope I can give proper answers to your question.

查看更多
女痞
3楼-- · 2020-02-02 19:10
public class Boss
{
   private string name;
   private List<Hashtable> dogs;
   private int limit;

   public Boss(string name, int dogLimit)
   {
      this.name = name;
      this.dogs = new List<Hashtable>();
      this.limit = dogLimit; 
   }

   public string Name { get { return this.name; } }

   public void AddDog(string nickname, Dog dog)
   {
      if (!this.dogs.Contains(nickname) && !this.dogs.Count == limit)
      {
         this.dogs.Add(nickname, dog);
         dog.AddBoss(this);
      } 
   }

   public void RemoveDog(string nickname)
   {
       this.dogs.Remove(nickname);
       dog.RemoveBoss(this);
   }

   public void Hashtable Dogs { get { return this.dogs; } }
}

public class Dog
{
   private string name;
   private List<Boss> bosses;

   public Dog(string name)
   {
      this.name = name;
      this.bosses = new List<Boss>();
   }

   public string Name { get { return this.name; } }

   public void AddBoss(Boss boss)
   {
      if (!this.bosses.Contains(boss))
      {
          this.bosses.Add(boss);
      }
   }

   public void RemoveBoss(Boss boss)
   {
      this.bosses.Remove(boss);
   }  

   public ReadOnlyCollection<Boss> Bosses { get { return new ReadOnlyCollection<Boss>(this.bosses); } }
}

The above maintains the relationship of Bosses can have multiple dogs (with a limit applied) and dogs having multiple bosses. It also means that when a boss is adding a dog, they can specify a nickname for the dog which is unique to that boss only. Which means other bosses can add the same dog, but with different nicknames.

As for the limit, I would probably have this as an App.Config value which you just read in before instantiating the boss object(s). So a small example would be:

var james = new Boss("James", ConfigurationManager.AppSettings["DogsPerBoss"]);
var joe = new Boss("Joe", ConfigurationManager.AppSettings["DogsPerBoss"]);

var benji = new Dog("Benji");
var pooch = new Dog("Pooch");

james.AddDog("Good boy", benji);
joe.AddDog("Doggy", benji);

james.AddDog("Rover", pooch);
joe.AddDog("Buddy", pooch);  // won't add as the preset limit has been reached.

You can obviously tweak this as you see fit, however, I think the fundamentals of what you are looking for are there.

  • Boss can have multiple dogs with limit
  • Dogs can have multiple bosses
  • Bosses can have different nicknames for same dog.
查看更多
Rolldiameter
4楼-- · 2020-02-02 19:11

Something like this; It still needs some finetuning though (make the collection private and add a readonly public accessor for it which returns a readonlycollection for instance, but you'll catch the drift.

public class Dog
{
    public List<Boss> Bosses;

    public void AddBoss( Boss b )  
    {
        if( b != null && Bosses.Contains (b) == false )
        {
            Bosses.Add (b);
            b.AddDog (this);
        }
    }

    public void RemoveBoss( Boss b )
    {
         if( b !=null && Bosses.Contains (b) )
         {
             Bosses.Remove (b);
             b.RemoveDog (this);
         }
    }
}

public class Boss
{
    public List<Dog> Dogs;

    public void AddDog( Dog d )
    {
         if( d != null && Dogs.Contains (d) == false )
         {
              Dogs.Add(d);
              d.AddBoss(this);
         }
    }

    public void RemoveDog( Dog d )
    {
        if( d != null && Dogs.Contains(d) )
        {
            Dogs.Remove (d);
            d.RemoveBoss(this);
        }
    }
}

In this way, you could model a many-to-many in your code where every Dog knows his Bosses, and every Boss knows his Dogs. When you need extra data in the helper table, you'll need to create another class as well.

查看更多
等我变得足够好
5楼-- · 2020-02-02 19:12

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.

查看更多
霸刀☆藐视天下
6楼-- · 2020-02-02 19:14

If you have a simple many-to-many linking table with foreign keys from each table in the relationship, then you would model it as you suggest: Boss has a collection of Dogs and Dog has a collection of Bosses.

If you have a many-to-many relationship with extra data, such as Nickname, then you would model that as two one-to-many relationships. Create an entity, such as DogBoss so that Boss has a collection of DogBoss and Dog has a collection of DogBoss.

查看更多
Animai°情兽
7楼-- · 2020-02-02 19:16

Not sure on what your asking for. But this is the table structure you want:

Dog Table

DOG_ID int PK DOG_Name varchar(50)

DogsPerBoss

ID int DOG_ID int BOSS_ID int DogNickName varchar(15)

Boss

BOSS_ID int PK BOSS_Name varchar(50)

查看更多
登录 后发表回答