Why SingleOrDefault result TOP(2) in SQL?
Solution 1:
It selects top 2 so that if there are actually 2 or more than 2 records in the database, an exception would be thrown. If it only selects top 1 there would be no way to error out.
Solution 2:
By asking for the SingleOrDefault
of a sequence, you are asking for this behaviour:
- if the sequence has exactly
0
elements, return thedefault
for the sequence's element type - if the sequence has exactly
1
element, return the element - if the sequence has more than
1
element, throw
Doing a TOP (1)
would empower the first two parts of this, but not the third. Only by doing a TOP (2)
can we differentiate between exactly 1
record and more than 1
record.
If you don't want or need the third part of the above behviour, instead use FirstOrDefault
.