Modeling parent-child relationships with classes

I am working on an easy document management system and looking for some help on how best to model certain relationships. In fact, I work with two "organizational units": Group and Type s. When a group and type are combined, they form a Link , to which Document then associated. Please note that a Group can be combined with more than one type, therefore, for example, you can have one Link consisting of "group 1" and "type A", and the second Link consisting of "group 1" and "group" , Type B '. In my opinion, this is not the best way to structure it, but at the moment I can not change it, so I need to do what they give me.

A Document may be a member of several Link s. For example, Document A may be a member of Link 10 and Link 13.

My problem is that sometimes I need to display one Document and a list of each Link to which the Document belongs, and in other cases I want to display one Link and list each Document that belongs to this Link .

I am not sure how to present the connection between these classes. I looked at the composite template, but I don’t think this will work for me, because it seems that the child has only one parent, where in my case the child can have several parents. Any help would be greatly appreciated.

0
design c #
source share
2 answers

What you are probably looking for is an n-to-m mapping. To be all OOP-y, you can store these mappings in each class:

 // actually write it using properties, information hiding etc instead... public class Document { public ICollection<Link> Links; } public class Link { public ICollection<Document> Documents; // this can be on Document as well, depending on what semantics you want... public void Add(Document d) { Documents.Add(d); d.Links.Add(this); } 
+2
source share

In terms of data, you describe many-to-many relationships, and these relationships usually require an entity that represents the relationship itself.

So, in your case, I would introduce the following object:

 public class DocumentLink { public Document Document { get; set; } public Link Link { get; set; } } 

Then each document can have a collection of DocumentLink objects, and each link can have a collection of DocumentLink objects.

Of course, you can introduce auxiliary methods for a more direct search for all links for a document and all documents for a link, but this is an essential structure that I will use under it.

+3
source share

All Articles