Чем отличается запрос данных из контекста с помощью Find() и Single().
Оба возвращают запрошенную сущность.
Некоторые примеры, которые я нашел в Microsoft, используют вариант Single, SingleOrDefault для запроса объекта. Некоторые используют метод Find.
Есть ли преимущества "производительности" при использовании одного над другим?
Актуалё там больше отличий. msdn.microsoft.com/en-us/library/gg696418(v=vs.113).aspx - find не должен запрашивать базу данных, если ответ может быть получен из уже загруженных объектов.
@bommelding Означает ли это, что Find будет принимать только «ID» (первичный ключ) в качестве аргумента? Так что на самом деле Single имеет более динамичное и лучшее применение.





Хотя они выглядят одинаково, в некоторых фундаментальных аспектах они очень разные.
Короче говоря, Find начинает поиск в локальном кэше контекста. Если совпадений не найдено, он отправляет запрос в базу данных.
Документация - ваш друг
Finds an entity with the given primary key values. If an entity with the given primary key values exists in the context, then it is returned immediately without making a request to the store. Otherwise, a request is made to the store for an entity with the given primary key values and this entity, if found, is attached to the context and returned. If no entity is found in the context or the store, then null is returned.
Queryable.SingleOrDefault - метод
Returns a single, specific element of a sequence, or a default value if no such element is found.
Queryable.FirstOrDefault - метод
Returns the first element of a sequence, or a default value if no element is found.
Тем более
The Find method on DbSet uses the primary key value to attempt to find an entity tracked by the context. If the entity is not found in the context then a query will be sent to the database to find the entity there. Null is returned if the entity is not found in the context or in the database.
Find is different from using a query in two significant ways:
- A round-trip to the database will only be made if the entity with the given key is not found in the context.
- Find will return entities that are in the Added state. That is, Find will return entities that have been added to the context but have not yet been saved to the database.
Обновлять
Does this mean that if the entitiy was already being tracked (through lazy loading), then Find would actually have a better performance advantange when trying to querying again?
Да, у него будет лучшая производительность
Означает ли это, что если объект уже отслеживался (через отложенную загрузку), тогда Find действительно имел бы лучшее преимущество в производительности при повторной попытке запроса?
Вы упустили параметры, которые (частично) ответили бы на ваш вопрос: Find () принимает только первичный ключ, варианты Single () принимают предикат. Обычно этот предикат сопоставляется с PK, и тогда производительность должна быть равной. Но Single всегда будет иметь немного больше накладных расходов, и в нем легко ошибиться.