Are there any differences between First and Single?
Are the two queries returned the same?
And what about performance between the two is the same?
Which of the two expressions is best to use?
Are there any differences between First and Single?
Are the two queries returned the same?
And what about performance between the two is the same?
Which of the two expressions is best to use?
Single
will throw an exception if the query returns more than one record. Only one record is expected.
First
will not throw exception for this case, and will return TOP 1
of result. One or more records are expected, but returns only the first.
Both throw exception when no record is returned.
As you see, they are two different goals. It's up to you to decide which one to use for each scenario.
The subtle difference between First
and Single
is that the latter imposes the rule that the query to the database should return only one record. To ensure such a constraint, the Single method emits a SQL TOP 2 clause. If two records are returned, it throws an exception. If zero records are returned, it throws an exception unless you use SingleOrDefault
, which has the same behavior as FirstOrDefault
.
Most recommended and First
, instead of Single
, for three reasons;
TOP 2
against the database; Single
is slightly slower than First
; and