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

前端 未结 12 1884
星月不相逢
星月不相逢 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:33

    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)

    0 讨论(0)
  • 2020-12-05 07:34

    In a relational model, the best way to model a many to many relationship (using your example of Dogs/Bosses) is to have three separate tables.

    One table for DOGS, one table for BOSSES (and each of these tables has a unique key), and the third table is usually a "junction table".

    This table will usually have at least two fields, one field for the foreign key for a Dog and the other field for the foreign key of a Boss. This way each Dog can have many bosses, and each Boss can have many Dogs.

    Now, when it come to modeling this in code in a more object-oriented manner, this is usually achieved by having a Dog class and a Boss class. As well as having the usual atomic properties for each of these objects, each one would also expose a property that is a collection of the other.

    So, for example, a Dog object would have a property called "Bosses". This property would expose a collection of Boss objects that are allocated to the specific Dog object (as defined in the junction table), and on the other side, each Boss object would expose a property called Dogs which would be a collection of Dog objects allocated to that specific Boss object (as defined by the junction table).

    Note that there may well be some "overlap" in these objects (i.e. one "dog" object may have "boss" objects that another "dog" object has), however, this is the traditional mechanism for translating a three-table many-to-many relational model into an object oriented one.

    0 讨论(0)
  • 2020-12-05 07:35

    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.

    0 讨论(0)
  • 2020-12-05 07:37

    Am I missing something or is the only code you need for this as follows:

    List<Bosses> BossList;
    
    class Dog {}
    class Boss { Dog[] Dogs; }
    

    You don't need to explicitly model the two-way relationship. It's implicit in the code structure. There may be other reasons to do so, but in general it is sufficient to have a one-way reference and a way to traverse the set of referencing objects.

    0 讨论(0)
  • 2020-12-05 07:39
    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.
    0 讨论(0)
  • 2020-12-05 07:39

    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.

    0 讨论(0)
提交回复
热议问题