Is there an "EF Core way" to consider local changes when querying a DbSet?
I'd like to respect the pattern of only calling DbContext.SaveChanges()
once per task, but it seems like the disconnect between local state and DB state can get complicated very quickly with queries going directly to the DB.
Example:
I update some elements in a DbSet
var results = db.Entity1.Where(e => e.date > expectedDate);
foreach(var result in results){
e.field = true;
}
And subsequently, query that same DbSet
db.Entity1.Where(e => e.field == false)
The second query returns the rows changed in the first block, as the query goes directly to the database without considering local changes. I'd like the second query to only return rows where e.field == false
in both the database and locally.
If you prefer to commit changes by logical groups, and at the same time avoid issues about querying the database and the Local
cache, then start by loading all entities that you need to work with in the Local
cache, work on the Local
cache only, and finally SaveChanges()
.
In your example, you would have this.
// Load entities whose date > expectedDate or whose field = false.
var result = db.Entity1.Where(e => e.date > expectedDate || e.field == false);
...
// Set field to true for entities whose date > expectedDate.
foreach (var entity in db.Entity1.Local.Where(e => e.date > expectedDate)) {
entity.field = true;
}
...
// Get entities whose field = false.
result db.Entity1.Local.Where(e => e.field == false)
...
db.SaveChanges();