开发者

Modelling Parent-Child Relationships with Classes

开发者 https://www.devze.com 2023-01-23 22:03 出处:网络
I am working on a lightweight document management system and am looking for some help with how best to model certain relationships.Essentially, I am working with two \"organizational units\": Groups a

I am working on a lightweight document management system and am looking for some help with how best to model certain relationships. Essentially, I am working with two "organizational units": Groups and Types. When a group and a type are combined they form a Link with which Documents are then associated. Note that a Group can be combined with more than one type, so for example you can have one Link composed of 'Group 1' and 'Type A' and a second Link composed of 'Group 1' and 'Type B'. In my opinion this is not really the best way to have structured it but at this point I'm unable to alter it so I have to make do with what I'm given.

A Document can be a member of multiple Links. So for example, 'Document A' can be a member of 'Link 10' and 'Link 13'.

My issue is that sometimes I will wa开发者_如何学编程nt to display a single Document and list every Link that Document belongs to, and other times I will want to display a single Link and list every Document that belongs to that Link.

I'm not sure how to represent the relationship between these classes. I've looked into the Composite Pattern but I don't think this will work for me because it seems to require that a child have only one parent, where in my case a child can have multiple parents. Any help would be appreciated.


From a data perspective you are describing a many-to-many relationship, and those relationships generally require an entity representing 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 could have a collection of DocumentLink objects and each Link could have a collection of DocumentLink objects as well.

Of course, you could introduce helper methods to more directly retrieve all links for a document and all documents for a link, but this is the essential structure that I would use underneath.


What you're probably looking for is an n-to-m mapping. To be all OOP-y, you can store these mappings within 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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号