简体   繁体   中英

Should objects of a collection member of parent object also reference the parent object?

So I have a ContactCardGroup class that contains a collection of ContactCardGroupMemberships:

 public class ContactCardGroup : AbstractEntity, IContactCardGroup
    {

        public ICollection<ContactCardGroupMembership> Members { get; protected set; }

And a ContactCardGroupMembership class:

 public class ContactCardGroupMembership : AbstractAspect
    {

        public long MembershipId { get; set; }

        public long GroupId { get; set; }

        public ContactCard Contact { get; set; }

        public bool IsPrimary { get; set; }

        public ICollection<ContactGroupRole> Roles { get; protected set; }

        public ContactCardGroupMembership()
        {
            this.Roles = new Collection<ContactGroupRole>();
        }
    }

So throughout the code it would be helpful if instead of GroupId, I had a ContactCardGroup member.... but is that not introducing a nasty circular reference especially around disposal/destruction.Is there a rule/pattern for such things?

Seems like ever since I installed ReSharper I no longer have any confidence in any of the coding choices I make ;(

You can have circular references, and they can be very useful. Most ORMs deal with them nicely.

However, if you use serialization libraries, then they can be a bit tricky and often don't like circular references.

But whether you should or shouldn't use them depends a lot on the problem you are solving.

Two (or more) things that hold references to each other (an object graph) won't keep themselves alive if that graph becomes isolated from a root reference. However you can accidentally end up holding on to large graphs of things just by holding a reference to one thing in the object graph.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM