January 27, 2025
I'm doing dotnet development for eight years, but just today I finally realised, what is the difference between .Find(..)
and .Where(..)
:
When Where
always makes request to database, Find
looks first by id in already cached entities and only if not found, checks in database.
I must have read about it previously, but only today I have found that one particularly big chunk of a very important command works accidentally correctly because of that: we make a very big loop, in each iteration we create new entity with id from external source and saving to database happen only afterwards. Would we have used Where
, entries would be duplicated (and exception thrown), but with Find
it's possible to get cached version, that was not yet saved to database.
Here is small example that demonstrates what I mean:
public record Person(int Id, string Name);
using var db = new AppDbContext(); db.Database.EnsureCreated(); db.Peoples.Add(new Person(60, "John")); db.Peoples.FirstOrDefault(p => p.Id == 60); // will return null var jackByFind = db.Peoples.Find(60); // will return entity
It is also possible to make query to cache using DbSet<T>.Local.Where(..)
, but afaik there is no straightforward way to make complex query by non-key parameters to cached version and, if not found - to database.