Different between DbContext.Find() and DbContext.SingleOrDefault() Entity Framework Core

c# entity-framework entity-framework-core

Question

What is the different when query data from context using Find() and Single(). Both return the entity being requested.

Some example I found on Microsoft are using Single, SingleOrDefault variation to query for entity. Some uses Find method.

Are there any "performance" advantanges when using one over the other?

1
0
10/31/2018 7:46:57 AM

Accepted Answer

Although they look the same they are very different in some fundamental ways

In short, Find starts by searching in the local cache of the context. If no match are found then it sends a query to the db.

Documentation is your friend

DbSet.Find Method

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 Method

Returns a single, specific element of a sequence, or a default value if no such element is found.

Queryable.FirstOrDefault Method

Returns the first element of a sequence, or a default value if no element is found.

More-so

Querying and Finding Entities

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.

Update

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?

Yes it will have better performance

5
10/31/2018 8:02:28 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow