Why does the Entity Framework’s DbContext.Find() generate a query with select top 2 and a derived table? By definition, the query is looking up by primary key which should be unique.
Why does the Entity Framework’s DbContext.Find() generate a query with select top 2 and
Share
Findchecks first if the entity with the given key is already in the context. If not it queries the database. Possibly it uses in this case a LINQ query usingSingleOrDefault.SingleOrDefaulttranslates toSELECT TOP 2to be able to throw an exception if the result has more than one entity.So, why doesn’t
FinduseFirstOrDefault(which would translate toSELECT TOP 1). I don’t know, but I would guess thatFindwants to check that the entity is really unique in the database. It should – because it’s the primary key the query uses – but model and database could be out of sync because someone changed the primary key in the database, for example: added a column to a composite key in the database but not in the model.Really just a hypothesis. Only EF development team probably can answer what’s exactly the reason.
Edit
If I do this as described above (add column to composite key in DB and add a record with the same value in the first key column) and call then
Find, I get the exception……and this stacktrace:
So, it looks that
Findindeed usesSingleOrDefault.