I was coding a very simple case with 2 classes: Parent and Child. Parent has n children, and children has 1 Parent. I set up a bidirectional relationship between them.
I was trying to add a business rule to my parent, that rule checked for equality between the child's parent and the instance handling the call. It returned false when it should have returned true. So I simplified everything to get to the root of the problem. So I tested the same equality outside the POCO and it returned true:
Parent parent0 = session.Load<Parent>(0);
Child child = session.Load<Child>(0);
bool externalTest = parent0 == child.Parent;
I then coded a method for my Parent to test the exact same thing:
bool internalTest = parent0.IsRelated(child);
... Parent Class code
public virtual bool IsRelated(Child child)
{
return child.Parent == this;
}
...
And it returns false... I just don't get it. It's the exact same code.
More info:
So to get more info, I modified my test:
Parent parent0 = session.Load<Parent>(0);
Child child = session.Load<Child>(0);
bool externalTest = parent0 == child.Parent;
System.Diagnostics.Debug.WriteLine("outside parent: " + externalTest);
System.Diagnostics.Debug.WriteLine("Number of parent instances before call to IsRelated:" + Parent.NumberOfInstances);
parent0.IsRelated(child, parent0);
System.Diagnostics.Debug.WriteLine("Number of parent instances after call to IsRelated:" + Parent.NumberOfInstances);
... Parent Class code
public virtual void IsRelated(Child child, Parent sameAsThis)
{
bool internalTest = child.Parent == this;
System.Diagnostics.Debug.WriteLine("inside parent:" + internalTest);
bool sameTest = sameAsThis == this;
System.Diagnostics.Debug.WriteLine("this should equal sameAsThis:" + sameTest);
}
...
I passed the parent instance directly to itself and verify it was the same instance. Well it's not, I get another instance created when I enter the IsRelatedMethod.
Here are my test results:
outside parent: True
Number of parent instances before call to IsRelated:1
inside parent:False
this should equal sameAsThis:False
Number of parent instances after call to IsRelated:2
What am I doing wrong ?
For detailed mapping files and pocos, see (http://stackoverflow.com/questions/13253459/relationships-fixup-in-entityframework-vs-nhibernate)