Hi all,
I have the problem with parent-child one-to-many asociation. My test classes are following:
Person (m_Pets 1-*> Pet, m_Name)
Pet (m_Owner *-1> Person, m_Name)
Constructor of Pet id following:
Code:
Pet(Person owner, string name) : base() {
m_Name = name;
m_Owner = owner;
m_Owner.Pets.Add(this);
}
Now, I have following strange behavior please read the code and the output:
Code:
Person p = pf.FindById(12); // "pf" is some factory class, "p" already has 2 pets
Debug.WriteLine(p.Pets.Count); // output is "2"
Pet x = new Pet(p, "Azor");
Debug.WriteLine(p.Pets.Count); // output is "3"
xf.FindAll(); // "xf" finds all instances of "Pet" using query by critera, automatic flush occure before
Debug.WriteLine(p.Pets.Count); // output is "3"
It works fine. The second try, using explicit Save method on ISession (rollback before):
Code:
Person p = pf.FindById(12); // "pf" is some factory class, "p" already has 2 pets
Debug.WriteLine(p.Pets.Count); // output is "2"
Pet x = new Pet(p, "Azor");
Debug.WriteLine(p.Pets.Count); // output is "3"
currentSession.Save(x); // explicitly saving new Pet
Debug.WriteLine(p.Pets.Count); // output is "3"
It is again fine, until I remove first and second Debug.WriteLine (rollback before):
Code:
Person p = pf.FindById(12); // "pf" is some factory class, "p" already has 2 pets
Pet x = new Pet(p, "Azor");
currentSession.Save(x); // explicitly saving new Pet
Debug.WriteLine(p.Pets.Count); // output is "4"
Now, you can see the wrong number of pets in the person collection. "Azor" is twice here. In database, everything is OK.
I'll try to smumarize my problem:
When I manage many-to-one collection in the constructor of "one" side by adding "this" to collection on "many" side, and only when this collection is lazy and it was not loaded from database before, and then explicitly save new "one" side using the "Session.Save", in the collection of many side I then have the new item twice. The collection is mapped as bag and inverse. If it is mapped with cascade "save-update" and the new item is flushed automatically to database, everything is fine.
Do someone know where can be the problem? I can send more sources if someone can examine it.
Many thanks! David[/b]