Joe
Joe

Reputation: 4183

Changes in foreach not retained

VS 2105, MVC5 EntityFramework 6 code first project

I successfully populate an IEnumerable (tried IQueryable also) of my ViewModel and then modify in a foreach loop.

If I step through the foreach the fields are updated, but when I examine the individual ViewModel in the IEnumerable the changes do not persist.

foreach:

foreach (var app in applVms) {  app.Preliminary = true; }

(I actually am making additional queries to child tables but I've simplified for this post)

Preliminary is false before and after the foreach but is set true inside the foreach.

Populating ViewModel:

  IEnumerable<ApplicationVm> applVms;
  applVms = from app in _db.Applications
            select new ApplicationVm { ... Preliminary = false, ...  };

Upvotes: 1

Views: 96

Answers (1)

Yacoub Massad
Yacoub Massad

Reputation: 27861

Since your applVms enumerable is based on a LINQ query, then it uses deferred execution which means that the query is not executed until you enumerate over the results.

Also, every time you enumerate over applVms, the results are calculated again (the query is executed another time).

When you looped the first time via foreach, you got one set of objects, and then you modified these objects.

When you enumerated over applVms to see the results (this is the second time you enumerate), that gave you a totally new collection of objects (by executing the query again).

To verify this use the following code:

IEnumerable<ApplicationVm> applVms;
applVms = (from app in _db.Applications
            select new ApplicationVm {Preliminary = false}).ToList();

//foreach here

This will enumerate the enumerable once and put it in a list so that future enumerations will use the same collection.

Upvotes: 3

Related Questions