WIP
Code samples for using .Find method for Entity Framework Core.
See also repository for .NET Core
Single() | SingleOrDefault() | First() | FirstOrDefault() | Find() | |
---|---|---|---|---|---|
Description | Returns a single, specific element of a sequence | Returns a single, specific element of a sequence, or a default value if that element is not found | Returns the first element of a sequence, or a default value if no element is found | Returns the first element of a sequence, or a default value if no element is found | Finds an entity with the given primary key values. If an entity with the given primary key values is being tracked by the context, then it is returned immediately without making a request to the database. Otherwise, a query is made to the database 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, then null is returned |
Exception thrown when | There are 0 or more than 1 elements in the result | Returns a single, specific element of a sequence, or a default value if that element is not found | There are no elements in the result | There are no elements in the result | Not found |
When to use | If exactly 1 element is expected; not 0 or more than 1 | When 0 or 1 elements are expected | When more than 1 element is expected and you want only the first | When more than 1 element is expected and you want only the first. Also it is ok for the result to be empty | It’s a DbSet method and executes immediately |
- Microsoft Visual Studio 2017 or higher
- SQL Server Management Studio
- Intermediate level knowledge
- Working with Entity Framework Core
- Working with C#