I have a query to the database that returns results and I have an IEnumerable that contains another IEnumerable and in the Model Populator I do something like
List<Parent> parents = Result1;
List<Children> children = Result2;
And then
foreach (parent p in parents)
{
p.MyChildren = children.Where(x => x.ParentId == p.Id);
}
I have debugged so far and the data are correct by the time I return the model both during the loop and also at the final model which contains the models.
However, on the controller I get a list of parents and they ALL have the same children collection, even though they were correct a moment before.
That means each parent has the same random collection in “MyChildren” and not the collection that belongs to them.
My view models have no static variables anywhere and there is no other object manipulation going on from the model to the controller.
Something really odd going on with the references and I am not sure how to resolve it.
Any ideas?
Try adding
ToList()to the right hand side, when setting the children:The result of
Whereis anIEnumerable, and the actual retrieval of the items is deferred. That means if something changes later,parent.MyChildrenchanges. AddingToArray()forces the enumeration to happen immediately.Update per Servy’s comment
You also have to create a local (inside the
foreachblock) copy ofp.Id(updated above). This problem is called “accessing a modified closure” More info: for example. See also here for more background, including an answer from Eric Lippert where he describes modified closures as one of the worst “gotchas” in C#.