Finding tracked entities by primary key in EF Core
In EF Core, the DbSet
class has a Find<TEntity>(params object[] keyValues)
method to find an entity by primary key values. If the entity is being tracked already then it is returned, otherwise it is retrieved from the database.
I was looking for a similar FindTracked
method that would not query the database if the entity is not found, but as of version 3.1 there is no public API to do that.
One way to circumvent the problem is to iterate over ChangeTracker.Entries<TEntity>()
but it is inefficient and could degrade performance.
A better way is to use an internal API called StateManager
that is actually used by DbSet.Find(...)
under the hood. I found this snippet in a GitHub issue discussing this feature:
var stateManager = context.GetService<IStateManager>();
var key = context.Model.FindEntityType(typeof(TEntity)).FindPrimaryKey();
var entity = stateManager.TryGetEntry(key, new object[] { myKeyValue })?.Entity;