I am using linq to select a bunch of objects by Id through a facade object. This facade has a function GetObjectById(string id) which returns a MyObject. I select a bunch of object in one query based on a list of ids:
IEnumerable<MyObject> objects =
from id in ids
select facade.GetObjectById(id);
Then later I set some value on my objects like so:
foreach(MyObject object in objects)
{
object.someValue = "banaan";
}
Later when I inspect the objects IEnumerable, someValue is not set to “banaan”.
It looks like it has something to do with the deferred execution of linq because when I put .ToList() behind the first query I does work. However, I thought I should be able to do something like this. What am I doing wrong here? Or is my understanding of how you should use linq wrong?
Thanks in advance.
Sure it is the problem of deferred execution. If the query is executed again it will again call your facade method during and if the facade method loads data from somewhere (= create new instances) your former changes are lost. Your
foreachis first execution and inspection outside of the firstforeachis second execution.You must call
ToListif you want to operate on the same instances in such scenario.