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

前端 未结 12 1975
星月不相逢
星月不相逢 2020-12-05 07:12

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

12条回答
  •  醉梦人生
    2020-12-05 07:39

    public class Boss
    {
       private string name;
       private List dogs;
       private int limit;
    
       public Boss(string name, int dogLimit)
       {
          this.name = name;
          this.dogs = new List();
          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 bosses;
    
       public Dog(string name)
       {
          this.name = name;
          this.bosses = new List();
       }
    
       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 Bosses { get { return new ReadOnlyCollection(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.

提交回复
热议问题