3.5.1 Getting parent reference from child.

3.5.1 Getting parent reference from child.

Old forum URL: forums.lhotka.net/forums/t/5131.aspx


tetranz posted on Monday, July 21, 2008

(from my previous thread today)
RockfordLhotka:

Yes, exactly. And all the parent-child event hookups for event cascading, and resetting the Parent reference on deserialization. All the hard-to-remember things you had to do to make parent-child really work are now automatic.


Something I'm not quite clear on ...

If I have, like in that test today, an EditableRootParent with an EditableChildList with EditableChild objects, is there now a built-in way of getting a reference to the RootParent from the child?

I know the child's Parent property is a reference to the list but I don't know how to get to the root. I think it's probably something to be avoided if possible but rightly or wrongly, I find myself needing to do that sometimes.

I usually put a reference to the root in the list and use the child's parent to navigate to it. That property needs to be not undoable and (I think) not serializable to avoid serialization loops. I'm never quite sure what the best practice is. I guess the same question could apply if it's a read-only list.

Ross

RockfordLhotka replied on Monday, July 21, 2008

CSLA only maintains a Parent property that goes one level up. If you want to go higher you'll need to do that yourself. The easiest way though, is probably not to manage your own reference, but to use the one provided by CSLA. So in your collection (child of the root) you could do:

internal object Root
{
  get { return this.Parent; }
}

Then in your child objects you could do this.Parent.Root to get to the "real" parent.

(you might want to pre-cast the value(s) or vary this pattern a little - but hopefully you get the idea)

Copyright (c) Marimer LLC