Daelmo,
I was using your suggested code when I experienced the strange behaviour. It does not work!
I'll try to give an example of what I encountered:
Suppose you have two tables in the database: Parent and Child. Parent can have one-to-may children.
E.g.
Parent: Peter (with PK = 1).
Child: Mary (with PK = 1), Suzy (with PK = 2) and John (with PK = 3).
When you retrieve Peter from the database and enumerate the children, the order of the children in the collection is by PK.
When instead you retrieve a child from the database, and then use code like the one you are suggesting, the following will occur:
for (int PK = 1, PK <= 3, PK++)
{
ChildEntity child = new ChildEntity(PK);
if (child.Parent.Child[0].Id == PK)
{
Console.WriteLine("PK {0} is first", PK);
}
}
This wil result in
PK 1 is first
PK 2 is first
PK 3 is first
being shown on the console.
When you inspect the collections of the Parent.Child, the order of the children in the collection depends on the child via which the parent is accessed:
PK 1, then the order is 1, 2, 3
PK 2, then the order is 2, 1, 3
PK 3, then the order is 3, 1, 2
This explains why using the code you suggest does not work properly.
Perhaps this behaviour depends on the database being used? I'm using SQLServer 2005.
Hope this clarifies it better
Jan