Any particular reason why we are using DbSet.Find()
public virtual T GetById(object id)
I've tried on a project where we have 10K orders where StoreService.GetStoreById()
is running very slow. After a profiling in Visual Studio, it turned out that
is causing the slowness.
I then change to Enumerable.FirstOrDefault()
and the performance is greatly improved (about 3 - 4 seconds faster).
There's a post on StackOverflow:
that talks about the slowness of
Find calls DetectChanges internally, SingleOrDefault (or generally any query) doesn't. DetectChanges is an expensive operation, so that's the reason why Find is slower (but it might become faster if the entity is already loaded into the context
because Find would not run a query but just return the loaded entity).
I believe we can safely change DbSet.Find()
, unless there's any special feature we need from
But "Find" won't call database if a record is already loaded. We should check whether FirstOrDefault calls database twice if we call this method for same entity and ID twice