'EF Core reload all entities for an entity type
In EF Core you can "reload" an Entity from the data store to pickup any changes.
An example of why you might need to do that is if you need to resolve a DB concurrency exception on SaveChanges.
This does work ok for one record...
EntityEntry<T> entityEntry = GetEntity(123);
entityEntry.Reload();
The only problem is, the Reload() executes a SQL statement per entityEntry.
So, if you want to refresh a set of entityEntry, you get a SQL statement per entry.
Whereas, the normal context.Set<T>().Load(); executes one SQL statement that retrieves all of the rows.
With a small number of entityEntry, the performance hit is negligable; but anytime I see a RBAR design approach, it raises a red flag for me.
Question: other than a RBAR loop
foreach (var e in context.ChangeTracker.Entries<T>)
{
e.Reload();
}
is there a way to re-execute the context.Set<T>().Load(); to reload the entries as a set?
Note: I am using the
context.Entry(e).State = EntityState.Detached
approach now; checking to see if there is something better that I have missed.
UPDATE 1
How I am testing
- Read data from database
- Add record to database
- Delete record from database
- Change record in database
- "reload" data
the result I am looking to get is
- entity for changed record is updated
- entity for deleted record is removed
- "optionally" entity for new record is added the Add is optional because that is not the designed behaviour of "reload", which is to update existing entity.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
