You are doing one of the big nonos of Entity Framework, you have a long lived DbContext. You should never do this.
In this case you are having issues with Entity Framework's Change Tracker. By default EF uses MergeOption.AppendOnly
.
This means by default, on each EF query, EF will only deserialize rows to objects, IFF the key does not match an object in the context's Change Tracker.
So given that you are using the same instance of the EF context each loop, EF just uses the cached values each time you do a query (the SQL runs, but EF does not create or alter the object as you expect). This is entirely expected, if you adhere to the rule that EF contexts are short lived.
To fix this you have several options.
- Instantiate a new EF context (and change tracker) each loop.
- Tell EF to use the
MergeOption.OverwriteChanges
on each query. - Tell EF not to use the change tracker AT ALL (this disables Write Access, but is much faster).